How to implement scroll to bottom functionality in React?

By Prajwal Haniya

Techletter #43 | September 16, 2023

Scroll-to-bottom functionality is one of the features that you would need while developing a web-based chat application. Why? Because, as the messages increase you make the view scrollable. But, every time the user visits a chat, he/she will start at the top, and it is irritating for the user if he/she always needs to scroll down manually to see the recent messages. So, in this letter, I will try to explain how you can implement scroll-to-bottom functionality in your React application.

In the below example, you can see an array of objects which you need to display to the user.

const data = [
    {
        id: 1,
        message: 'Message 1'
    },
    {
        id: 2,
        message: 'Message 2'
    },
    //....
    {
        id: 11,
        message: 'Message 11'
    },
];

So, now let’s create a functional component, which renders the list of 11 items. So let’s assume the height of the div cannot show all the 11 items in one shot. So you specify a height and make it scrollable.

function ScrollComponent() {
        const chatboxRef = useRef(null);

        const scrollToBottom = () => {
            if (chatboxRef.current) {
                chatboxRef.current.scrollTop = chatboxRef.current.scrollHeight;
            }
        };

        const getData = () => {
            // get data from API call
            // once you have the result call the scroll to bottom function
            setTimeout(() => {
                scrollToBottom();
            }, 100); 
        }
    return (
        <div id="chatbox" ref={chatboxRef} style={{ height: height, overflow: 'auto' }}>
            {data && data.length > 0 ? (
                    <div>
                        {
                            data.map(item => (
                                <div key={data?.id}>
                                    // YOUR UI for message
                                </div>
                            ));       
                        }
                    </div>
                ) : null}
        </div>
    )
}

When you call the scrollToBottom() function, the div is scrolled to the bottom of its height. You can call the function using useEffect() or can call it after an event occurs.

Now, let’s understand what is useRef() hook & how it works?

useRef() hook provides a way to create and hold a mutable reference to a DOM element or any other value that you want to persist across renders without causing re-renders when the value changes.

What do you mean by a mutable reference?

A mutable reference refers to a reference (or pointer) to a value in memory that can be changed after it has been initially set. In the context of useRef in React:

One of the simple examples of the react useRef() hooks can be as shown below

import React, { useRef, useEffect } from 'react';

function MyComponent() {
  const myInputRef = useRef(null);

  useEffect(() => {
    // Focus on the input element when the component mounts
    myInputRef.current.focus();
  }, []);

  return (
    <div>
      <input type="text" ref={myInputRef} />
      <button onClick={() => myInputRef.current.value = ''}>Clear Input</button>
    </div>
  );
}

So, in this way, you can implement a scroll-to-bottom functionality using useRef hook.