šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

Scroll an element into view at button click in React

One of the easiest ways to scroll to a React element is by using a mix of the useRef() hook and the scrollIntoView() API.

We will see how can we do this by building the below example:

We will start with a simple stateless component:

const App = () => {
  return (<>
      <p>scroll down a lot to see a red div ā†“ā†“ā†“
      <button onClick={doClick}>or click this button</button></p>
      <div className="red">Red Div</div>
  </>)
}

We will need to add the useRef() hook so that we can point to the targeted React element:

const App = () => {
    const ref = useRef(null);
    //...
    <div ref={ref} className="red">Red Div</div>
}

With this in place, we can easily use the scrollIntoView API to bring that element into view.

ref.current?.scrollIntoView()

The full code is below and you can check out the working codepen here:

const App = () => {
  const ref = useRef(null);
  const doClick = () => ref.current?.scrollIntoView({behavior: 'smooth'})

  return (<>
      <p>scroll down a lot to see a red div ā†“ā†“ā†“
      <button onClick={doClick}>or click this button</button></p>
      <div ref={ref} className="red">Red Div</div>
  </>)
}

We can add some extra parameters to scrollIntoView() like:

  • scrollIntoView({behavior: 'smooth'}) to add a natural animation the scroll movement
  • or {block: "start", inline: "nearest"} to set behaviors such as the top of the element to be aligned to the top of the visible area of the scrollable ancestor

Check out the full documentation here.

As a final thought when working with scrolling elements, you may also want to check out the Intersection Observer API in Javascript for performance improvements.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

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