How to start at the bottom of a page and scroll upwards in reactJS

Viewed 101

so i'm making a react webApp that has a group-chat feature. Everything is going so well apart from one thing. I wan't the chat to default to the bottom of the screen once entered, then be scrolled upward to view older messages. i've tried the whole useEffect scroll to bottom nonsense and it works alright, except it would be a lot nicer if i could have my chat more like whatsApp. i need a cleaner fix and all i'm finding is half assed solutions, anyone know how whatsApp do it?

Here's what i'm using currently, incase anyone wants a quick fix. i just throw this into useEffect and at the end of my 'getMessages' fetch.

const scrollToBottom = () => {
    window.scrollTo({
        top: document.documentElement.scrollHeight,
        behavior: 'auto'
        /* you can also use 'auto' behaviour 
           in place of 'smooth' */
    })
};
1 Answers

I use this

function ScrollToBottom(){
  const elementRef = useRef();
  useEffect(() => elementRef.current.scrollIntoView());
  return <div ref={elementRef} />;
};

Then you just call it at the end of the messages.

<p>some message</p>
<p>another message</p>
<ScrollToBottom />
Related