šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

Autoscroll to bottom in React

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.
Autoscroll to bottom in React

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.

šŸ“– 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.


2 Replies

Leave a Reply

Your email address will not be published. Required fields are marked *