Scroll to an element on click in React

avatar

Borislav Hadzhiev

Sun Apr 24 20222 min read

banner

Photo by Lua Valentia

Scroll to an element on click in React #

To scroll to an element on click in React:

  1. Set a ref prop on the element you want to scroll to.
  2. Set the onClick prop on the other element.
  3. Every time the element is clicked, call the scrollIntoView() method on the ref object.
App.js
import {useRef} from 'react'; export default function App() { const ref = useRef(null); const handleClick = () => { ref.current?.scrollIntoView({behavior: 'smooth'}); }; return ( <div> <button onClick={handleClick}>Scroll to element</button> <div style={{height: '155rem'}} /> <div ref={ref}>Some content here</div> <div style={{height: '155rem'}} /> </div> ); }

scroll to element on click

We initialized a ref using the useRef hook.

The useRef() hook can be passed an initial value as an argument. The hook returns a mutable ref object whose .current property is initialized to the passed argument.

Notice that we have to access the current property on the ref object to get access to the div element on which we set the ref prop.

When we pass a ref prop to an element, e.g. <div ref={myRef} />, React sets the .current property of the ref object to the corresponding DOM node.

We set the onClick prop on the button element, so every time it's clicked, the handleClick function is invoked.

App.js
const handleClick = () => { ref.current?.scrollIntoView({behavior: 'smooth'}); };

In the handleClick function, we used the scrollIntoView method to scroll to the div element on which the ref prop is set.

The behavior property specifies whether the scrolling should animate smoothly (smooth), or happen instantly (auto).

The default value for the behavior property is auto.

Every time the button is clicked, the scrollIntoView() method is invoked on the element on which we set the ref prop, and the element is made visible to the user.

Use the search field on my Home Page to filter through my more than 1,000 articles.