scrollIntoView() is a JavaScript method that scrolls to element it is called on. Since React is a JavaScript library, we can use it to scroll to element in React.

Scroll to element on click

Here’s an example where we scroll to element when user clicks a button:

export default function App() {
 const subheading = useRef(null);
 return (
   <div className="App">
     <button onClick={() => subheading.current.scrollIntoView()}>
       Scroll to Subheading
     </button>
     <h1>Introduction</h1>
     <p>...text</p>
     <p>...text</p>
     <h2 ref={subheading}>Sample h2 heading text</h2>
   </div>
 );
}
  1. We create a variable to store an empty ref.
  1. In JSX, we set the ref prop to the variable that holds empty ref. From now on, we can use the variable to reference the element in JavaScript.
  1. We set the onClick prop to an event handler that calls scrollIntoView() method on current property of the ref.

To scroll more smoothly, pass options object as an argument to the scrollIntoView() method, with a behavior property set to smooth.

Other options include block, which allows you to specify the part of element to scroll to. It can be start, center, or end. You can use this option to scroll to the bottom of the page.

You can go see a full list of options and details on scrollIntoView() method on MDN docs.

Scroll to element on mount

In functional components, we’ll use the useEffect() hook to scroll to element when it mounts.

export default function App() {
 const subheading = useRef(null);
 useEffect(() => subheading.current.scrollIntoView(), []);
 return (
   <div className="App">
     <button onClick={() => subheading.current.scrollIntoView()}>
       Scroll to Subheading
     </button>
     <h1>Introduction</h1>
     <p>...text</p>
     <p>...text</p>
     <h2 ref={subheading}>Sample h2 heading text</h2>
   </div>
 );
}

First argument of the useEffect() hook is a callback function, which should call scrollIntoView() method on the element.

Second argument to the useEffect() hook should be an empty array, so the callback function runs only when component is mounted.

In React class components, you can implement this feature by calling setScrollIntoView() on the element in a componentDidMount() lifecycle method.

UX