简体   繁体   中英

Scroll to bottom of div automatically on page load

I have a chat application in react and have used npm package react-scroll-to-bottom until now. But it's not maintained and throwing warnings so i thought it should not be too hard to write this myself. I'm following various answers on stackoverflow but cant seem to get it right.

It should just scroll to the bottom of the container as the page loads.

Any ideas what i'm doing wrong? Thanks in advance! EDIT: now i have a div at the end of the tree which has the ref because i thought it would be easier to scroll to that instead of trying to tell a div to scroll inside it.

const chatHistoryRef = React.useRef();

 React.useEffect(() => {
    window.scrollTo(0, chatHistoryRef.current.offsetTop);
  }, [chatHistoryRef]);

Your useEffect does not have any dependencies, so if the ref changes (as in, the div gets rendered) the effect will not be run. Dependencies are set in a second parameter as an array, like so:

useEffect(() => {
// do something with chatHistoryRef.current
}, [chatHistoryRef.current])

Found the solution. As i'm working with polling in my app right now i only get chat messages every two seconds. So my function was in fact scrolling, but there just wasnt anything to scroll away from. :)

This is my solution. Thanks everyone for the help. By adding length to message dependency this is only fired if there are new chat messages

  const chatHistoryRef = React.useRef();

  React.useEffect(() => {
    chatHistoryRef.current.scrollIntoView({
      behavior: 'smooth',
      block: 'end'
    });
  }, [chatHistoryRef, messages.length]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM