React: [useRef, scrollIntoView,] How to only autoscroll a specific div inside of an overflowing page?

10,975

Try this:

   messagesRef.current.scrollIntoView({
      behavior: "smooth",
      block: "nearest",
      inline: "start"
    });
Share:
10,975
bauervision
Author by

bauervision

Software engineer developing GUIs.

Updated on June 04, 2022

Comments

  • bauervision
    bauervision almost 2 years

    As you can see in my example

    const rootElement = document.getElementById("root");
    ReactDOM.render(<App />, rootElement);
    
    function App() {
      const items = ["this", "that", "those", "them", "these", "thisins"];
    
      const messagesRef = React.useRef(null);
      const scrollToBottom = () => {
        messagesRef.current.scrollIntoView({
          behavior: "smooth"
        });
      };
    
      React.useEffect(() => {
        if (messagesRef.current) {
          scrollToBottom();
        }
      }, [messagesRef]);
    
      return (
        // Page is overflowing, set height to mimic a full page
        <div className="App" style={{ marginTop: 70, height: 800 }}>
          {/* now set this div to overflow scroll with a small height */}
          <div style={{ overflowY: "scroll", height: 200, border: "solid" }}>
            {items.map(elem => (
              <div style={{ border: "solid", borderColor: "green", padding: 20 }}>
                {elem}
              </div>
            ))}
            {/* Set last element within this div to be the ref to scroll to */}
            <div ref={messagesRef} />
          </div>
        </div>
      );
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>
    
    <div id="root"></div>

    The page loads, and both the page and the nested scrolling div auto scroll.

    What I'm trying to do is only scrollIntoView the overflowing div I have set as my ref.

    I'm targetting the ref, and it is working, but how do I NOT scroll the parent element as well?

  • Shahmir
    Shahmir over 3 years
    How to give margin-top(offset) ?