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
If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

6 Responses

  1. Amir says:

    Thanks for this great article. Very simple and straightforward solution to an otherwise annoying problem.

  2. Efe says:

    Thanks mate !

  3. avenue17 says:

    I with you completely agree.

  4. avenue17 says:

    In it something is. Thanks for an explanation, I too consider, that the easier the better …

  5. novopet says:

    You are absolutely right. In it something is also to me this idea is pleasant, I completely with you agree.

Leave a Reply

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