Auto scroll to the bottom in a react chat application

Today we’ll show you how to auto scroll to the bottom in a react chat application. In this article, we will create a react app to simulate the chat application and automatically set the scroll position on the new message.

There are many packages available to achieve this functionality but we will use the DOMNodeInserted JavaScript event to manage the scroll position in ReactJS.

Steps to implement chatbot auto scroll to the bottom

  1. Create a react application
  2. Create a chatbot design
  3. Write a function to generate dummy messages
  4. Manage auto scroll to the bottom
  5. Output

1. Create a react application

First, we will create a react application using the create-react-app package. Run the following command to create a react app.

2. Create a chatbot design

Now, let’s create a simple chatbot design to simulate the functionality. We’ll consider the three parts such as header, messages and footer (input area) in the chatbot. Use the following code for the design.

App.js

index.css

3. Write a function to generate dummy messages

We have to write a function to generate dummy messages so we can simulate the chatbot responses. Check out the following code to generate messages.

4. Manage auto scroll to the bottom

To manage auto scroll to the bottom of the message list div, we will use the DOMNodeInserted javascript event along with the refs in React Hooks. Also, use the above function to send a dummy message every two seconds.

App.js

5. Output

Run the application and check the output in the browser.

Output - Auto scroll to the bottom in a react chat application - Clue Mediator
Output – Auto scroll to the bottom in a react chat application – Clue Mediator

That’s it for today.
Thank you for reading. Happy Coding..!!

Demo & Source Code

Github Repository StackBlitz Project

You may also like...

Leave a Reply

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