Last updated: Apr 7, 2024
Reading timeยท2 min

To scroll to the bottom of a div in React:
div.ref on the element at the bottom.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 the bottom every time messages change bottomRef.current?.scrollIntoView({behavior: 'smooth'}); }, [messages]); return ( <div> <h2>Top of the page</h2> <div> {messages.map((message, index) => { return <p key={index}>{message}</p>; })} <div ref={bottomRef} /> </div> </div> ); }

The code sample 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.
useEffect(() => { // ๐๏ธ Simulate chat messages flowing in setInterval( () => setMessages(current => [ ...current, 'Lorem ipsum dolor sit amet consectetur, adipisicing elit. Porro', ]), 600, ); }, []);
We initialized a ref using the useRef hook.
const bottomRef = useRef(null);
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.
current property on the ref object to get access to the div element on which we set the ref prop.useEffect(() => { // ๐๏ธ Scroll to the bottom every time messages change bottomRef.current?.scrollIntoView({behavior: 'smooth'}); }, [messages]);
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.
messages state variable as a dependency in our second useEffect hook, because we want the code in the hook to be rerun 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.
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 rerun and we call the
scrollIntoView() method to scroll to the bottom of the div and show the most
recent message.
I've also written a detailed guide on how to handle the onScroll event in React.
You can learn more about the related topics by checking out the following tutorials: