Categories
React Answers

How to scroll a div to be visible in React?

Spread the love

Sometimes, we want to scroll a div to be visible in React.

In this article, we’ll look at how to scroll a div to be visible in React.

How to scroll a div to be visible in React?

To scroll a div to be visible in React, we use the scrollIntoView method.

For instance, we write

import ReactDOM from "react-dom";
import React, { useRef } from "react";

const Comp = () => {
  const divRef = useRef(null);

  const scrollToDivRef = () => {
    const node = ReactDOM.findDOMNode(divRef.current);
    node.scrollIntoView({ block: "start", behavior: "smooth" });
  };

  return (
    <div>
      ...
      <div ref={divRef} />
    </div>
  );
};

to define the divRef and assign it to the div we want to scroll to.

Then we define the scrollToDivRef function that gets the node that’s assigned to the ref.

And then we call node.scrollIntoView to scroll to the div.

We set behavior to 'smooth' to do smooth scrolling.

Conclusion

To scroll a div to be visible in React, we use the scrollIntoView method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *