Scroll to the bottom of a div in React


Borislav Hadzhiev

Last updated: Apr 24, 2022


Photo from Unsplash

Scroll to the bottom of a div in React #

To scroll to the bottom of a div in React:

  1. Add an element at the bottom of the div.
  2. Set a ref on the element at the bottom.
  3. When an event occurs, call the scrollIntoView() method on the ref object.
import {useEffect, useRef, useState} from 'react'; export default function App() { const bottomRef = useRef(null); const [messages, setMessages] = useState([]); useEffect(() => { // 👇️ simulate chat messages flowing in setInterval( () => setMessages(current => [ ...current, 'Lorem ipsum dolor sit amet consectetur, adipisicing elit. Porro, quaerat eum id obcaecati, magnam voluptatum dolorem sunt, omnis sed consectetur necessitatibus blanditiis ipsa? Cumque architecto, doloribus mollitia velit non sint!', ]), 600, ); }, []); useEffect(() => { // 👇️ scroll to bottom every time messages change bottomRef.current?.scrollIntoView({behavior: 'smooth'}); }, [messages]); return ( <div> <h2>Top of the page</h2> <div> {, index) => { return <p key={index}>{message}</p>; })} <div ref={bottomRef} /> </div> </div> ); }

react scroll to bottom

The code snippet shows how to scroll to the bottom of a div every time a new chat message flows in.

The first call to the useEffect hook simulates new messages coming in every 600 milliseconds.

We initialized a ref using the useRef hook.

The useRef() hook can be passed an initial value as an argument. The hook returns a mutable ref object whose .current property is initialized to the passed argument.

Notice that we have to access the current property on the ref object to get access to the div element on which we set the ref prop.

When we pass a ref prop to an element, e.g. <div ref={myRef} />, React sets the .current property of the ref object to the corresponding DOM node.

We added the messages state variable as a dependency in our second useEffect hook, because we want the code in the hook to be re-ran every time the messages change.
useEffect(() => { bottomRef.current?.scrollIntoView({behavior: 'smooth'}); }, [messages]);

We used the scrollIntoView method to scroll to the div element at the bottom of the chat messages container.

The behavior property specifies whether the scrolling should animate smoothly (smooth), or happen instantly (auto).

The default value for the behavior property is auto.

Every time the messages change, the useEffect hook is re-ran and we call the scrollIntoView() method to scroll to the bottom of the div and show the most recent message.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.