🎁 The Js-Craft Guide to React is now available with a 30% off discount!

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.

10 Javascript AI projects with Langchain & React

Not sure what to build? Dive in with these Javascript AI projects! Learn how to build LLM powered apps using Langchain.js and React! Connect your apps to LLMs such as OpenAI, create agents, use vector databases, or setup AI context.

10 Javascript AI projects with Langchain & React

Not sure what to build? Dive in with these Javascript AI projects! Learn how to build LLM powered apps using Langchain.js and React! Connect your apps to LLMs such as OpenAI, create agents, use vector databases, or setup AI context.


One Reply

Leave a Reply

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

📘 The Guide to React Home Screencasts Best of Newsletter Search X

📘 - 10 Javascript AI projects with React and LangChain

Hi friend! Before you go, just wanted to let you know about the 10 Javascript AI projects ideas with React and LangChain FREE ebook.

One of the best ways to learn is by doing the work. Choose from these 10 project ideas and start working on topics such as:

  • How does LangChain work
  • Connecting to OpenAI LLM
  • Create AI Agents
  • Simple and Sequential Chains
  • Adding Memory (Chat Context)
  • Prompt Templates
  • Using OutputParsers and Tools for Agents
  • Work with Documents and more...

Keep building and see the new capabilities LLM models can add to your React app! Get all projects as an ebook right to your inbox!

X