Tuesday, 2 April, 2024 UTC


Summary

Hey folks! Let's see how we can make React automatically scroll to the bottom of a div or any other container.
For example, let's say we are building something like a logging screen or a chat system where new items are added every few seconds.
In a scenario like this, it would help if our app would automatically scroll to the bottom of the container so that the user can see the last added item.
Checkout the below video to see our final example in action:
If you want to skip ahead here is the full code and the live running app.
We will start with this basic setup:
// ❌ no automatic scroll at this point

const getNewRandomItem = () => ({
    id: Math.random().toString(16).substr(2),
    label: 'LABEL: ' + Math.random().toString(16).substr(2)
}) 

const App = ()=> {
    const [items, setItems] = useState([]);

    const handleAddClick = () => {
        setItems((items) => [ ...items,  getNewRandomItem()]);
    };

    return (<div>
        <ul ref={listRef}>
            {items.map( i => (
                <li key={i.id}>{i.label}</li>
            ))}
        </ul>
        <button onClick={handleAddClick}>Add item ({items.length})</button>
    </div>);
}
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.
In order to add the auto-scrolling we will:
  1. setup a useRef() for the container (in our case the ul)
  2. have the useEffect() hook watch for when new items are added
  3. when a new item is added, we get its reference by using the container's lastElementChild and we bring it into wiew with the scrollIntoView() method
The full code that will achieve this is below:
// 👍 adding the automatic scroll

const getNewRandomItem = () => ({
    id: Math.random().toString(16).substr(2),
    label: 'LABEL: ' + Math.random().toString(16).substr(2)
}) 

const App = ()=> {
    //1️⃣ setup a ref to the container
    const listRef = useRef(null);
    const [items, setItems] = useState([]);

    //2️⃣ watch for when new items are added
    useEffect(() => {
        //3️⃣ bring the last item into view        
        listRef.current?.lastElementChild?.scrollIntoView()
    }, [items]);

    const handleAddClick = () => {
        setItems((items) => [
            setItems((items) => [ ...items,  getNewRandomItem()]);
        ]);
    };

    return (<div>
        <ul ref={listRef}>
            {items.map( i => (
                <li key={i.id}>{i.label}</li>
            ))}
        </ul>
        <button onClick={handleAddClick}>Add item ({items.length})</button>
    </div>);
}
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. Having this reference we can just call the scrollIntoView() method on it.
listRef.current?.lastElementChild?.scrollIntoView()
Just, be sure to check if the list is not empty to avoid any errors.
As usual the code is on my Gitub and the running example here.