Categories
React Answers

How to Scroll to a Div to Make it Visible in React?

Spread the love

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

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

Scroll to a Div to Make it Visible in React

To scroll to a div to make it visible in React, we can use the scrollIntoView method to scroll the page to make the element we want visible.

For instance, we can write:

import { useRef } from "react";

export default function App() {
  const ref = useRef();
  return (
    <div>
      <button onClick={() => ref.current?.scrollIntoView()}>
        scroll into view
      </button>
      {Array(50)
        .fill()
        .map((_, i) => {
          return <div ref={i === 40 ? ref : undefined}>{i}</div>;
        })}
    </div>
  );
}

We call the useRef hook to create a ref for the element that we want to scroll to when we click the button.

Then we assign the ref to an element that we want to scroll to with the ref prop.

Next, we set the onClick prop of the button to a function that calls scrollInfoView on ref.current to scroll the element that’s assigned the ref into view.

ref.current has the element that’s been assigned the ref.

Conclusion

To scroll to a div to make it visible in React, we can use the scrollIntoView method to scroll the page to make the element we want visible.

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 *