Home > Enterprise >  React auto scroll to bottom of a div
React auto scroll to bottom of a div

Time:05-25

So currently I have this issue, I am in react Issue Gif

I want when the page load, it auto scrolls to the bottom of the messages box

This is my current code : https://sourceb.in/GU4IOYtB9H

CodePudding user response:

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

const Messages = ({ messages }) => {

  const messagesEndRef = useRef(null)

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

  useEffect(() => {
    scrollToBottom()
  }, [messages]);

  return (
    <div>
      {messages.map(message => <Message key={message.id} {...message} />)}
      <div ref={messagesEndRef} />
    </div>
  )
}
  • Related