What if we want to scroll to view the last element added to a React list? Or actually any array style elements?
See the below video for the full example:
We will start with this basic setup:
const App = () => {
const [items, setItems] = useState([]);
const handleAddClick = () => {
setItems((items) => [
...items,
{
id: Math.random().toString(16).substr(2),
label: "LABEL: " + Math.random().toString(16).substr(2)
}
]);
};
return (
<>
<button onClick={handleAddClick}>Add list item ({items.length})</button>
<ul>
{items.map((i) => (
<li key={i.id}>{i.label}</li>
))}
</ul>
</>
);
};
What the above code will do is generate some random items and add them to a list.
However when new items are added no scroll happens.
We have seen in a previous article how to scroll to a React element when a button is clicked, by using a combination of scrollIntoView()
view and the ref hook.
The ref.current
gives us access to the actual HTML element. Any element HTML element has a lastElementChild property that points to the element's last child. In the case of a list, this will point to the last element added to a list.
Therefore we can simply do something like this:
listRef.current?.lastElementChild?.scrollIntoView()
Where listRef
is the reference to our list.
You can check out below the full code:
const App = ()=> {
const listRef = useRef(null);
const [items, setItems] = useState([]);
useEffect(() => {
listRef.current?.lastElementChild?.scrollIntoView();
}, [items]);
const handleAddClick = () => {
setItems((items) => [
...items,
{
id: Math.random().toString(16).substr(2),
label: 'LABEL: ' + Math.random().toString(16).substr(2),
},
]);
};
return (
<>
<ul ref={listRef}>
{items.map((i) => (
<li key={i.id}>{i.label}</li>
))}
</ul>
<button onClick={handleAddClick}>Add list item ({items.length})</button>
</>
);
}
And here is the working codepen for this example.
📖 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.
📖 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.
This works fantastically. Thanks for the post!