I am writing a chat app using react. How to auto scroll a page to bottom when new content generated and the page is not scrolled to bottom

2024-03-27by@tim&@ChatGPT.Model: GPT-4
tim

I am writing a chat app using react. How to auto scroll a page to bottom when new content generated and the page is not scrolled to bottom

Avatar
Avatar

You can achieve automatic scrolling to the bottom of a page in a React app by using the ref attribute and the scrollIntoView method.

Here's an example code snippet that demonstrates how to auto-scroll a page to the bottom when new content is generated:

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

const ChatApp = () => {
  const messagesEndRef = useRef(null);

  const scrollToBottom = () => {
    messagesEndRef.current.scrollIntoView({ behavior: "smooth" });
  }

  // Call scrollToBottom on initial render and whenever new content is added
  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  return (
    <div>
      {/* Render chat messages here */}
      {messages.map((message, index) => (
        <div key={index}>{message}</div>
      ))}

      {/* Empty div that will be used as a reference to scroll to */}
      <div ref={messagesEndRef} />
    </div>
  );
};

export default ChatApp;

In this example, we create a useRef hook to create a reference to an empty div element that will be used as a reference for scrolling to the bottom. The scrollToBottom function uses the scrollIntoView method to scroll the div element into view with a smooth behavior.

We then call scrollToBottom on initial render and whenever new content is added to the chat messages. This will ensure that the page is auto-scrolled to the bottom whenever new content is generated.