Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 629
bauervision Avatar asked Dec 18 '22 14:12

bauervision


1 Answers

Try this:

   messagesRef.current.scrollIntoView({
      behavior: "smooth",
      block: "nearest",
      inline: "start"
    });
like image 140
NirG Avatar answered Dec 31 '22 02:12

NirG