Scroll to bottom of the chat in React
React is a perfect choice for building a chat web application. It’s not difficult to build, as long as you know some React features and basic UX principles of a web application. In this article, we want to discuss one of those essential UX features for chat applications built in React – scrolling to the bottom when there’s a new message added to the chat.
I got inspiration from scroll to bottom of the chat section on SimpleFrontEnd’s tutorial.
To set up this feature, you’re going to need a couple of things:
useState() hook to initialize the state
useRef() hook to store a reference to a JSX element
scrollIntoView() method to automatically scroll to the latest message (we’ll explain this in detail later)
A child component to render actual messages, let’s call it <Message>
So, essentially what we’re going to do is this:
Use the useState() hook to initialize a state variable – an array of strings. Every string is going to represent the text of already exchanged messages.
You can have an empty array and add strings by entering messages, but for demonstration of how ‘scroll to the bottom of the chat’ feature works, let’s have an array of existing messages.
Next is the scrollIntoView() method. It allows us to ‘scroll to’ a certain element in JSX. It takes two arguments – ref, to element to which we need to scroll, and the behavior for scrolling. I like to choose smooth for better animation.
Every time user enters a new message, we’re going to run a function that calls scrollIntoView() on the bottom of the <div> container. It will scroll to the bottom because the options object passed to the scrollIntoView() method allows you to specify which end of the element you want to scroll to. In this case, we need to see the bottom end of the <div>.
Finally, we actually need to display messages in the ‘chatbox’ (a simple <div> container). So we need to render a <Message> component for every message in the list, and any new messages entered by the user.
First, you need to create this child component, of course. Any basic structure will do just fine. Then you’re going to need a map() method to render every message in the state array.
However, there’s one thing missing – every time user clicks ‘Send’, we need to update the state variable to include the latest message as well.
As you remember, useState() returns the state variable, as well as the function to update it. We can simply use the function to update the messages array.
Obviously, the updated state variable should include all previous messages (all strings). We can use three dots for nesting all current state values, and add the new one as well.