Nowadays many web applications are overloaded with content. Sometimes you need to highlight certain elements or components by setting scroll position in React.

In this article, we’ll show you how to set scroll position when component mounts or when users click a button.

Set scroll position to element

Sometimes we need to set scroll position to one of the many elements on the page. To do that in React, first we need to create a ref (short for reference) for that DOM element.

In vanilla JavaScript, we use the getElementById() to reference a certain HTML element. In React, we use refs.

Since the introduction of hooks, I prefer to use functional components and the useRef() hook to create a ref.

If you want to set scroll position to a specific element in React, first create a variable to store a ref (an instance of useRef() hook).

const someElement = useRef()

Then in your JSX, choose the element you want to set scroll position for. Let’s say you have a paragraph (<p>) element. Set its ref attribute to previously defined variable that contains a ref instance.

export default function App() {
  const someElement = useRef();
  return (
    <div className="App">
      <p>Element one</p>
      <p>Element Two</p>
      <p ref={someElement}>Element Three</p>
    </div>
  );
}

Finally, we have a ref tied to a React element.

We can set scroll position to this element when user clicks a button, when the component first mounts, or when a certain state variable changes.

First, let’s explore how to set scroll position when user clicks a button.

We have a variable that contains a ref, and we have established a connection between ref and the React element.

Next, we need to create a <button> element and set an onClick event handler for the button. Every time user clicks a button, the event handler should call the function that sets scroll position to this element.

scrollTo() method to set scroll position

Finally, we need to create the function takes element as an argument, and sets scroll position to that element. We can reuse this function to set scroll position to various React elements and components.

Let’s name it setScrollPosition.

Function body should call the scrollTo method on window interface, and pass it an options object with two properties: top (where to set position) and behavior (basic animation).

Let’s look at the code:

const setScrollPosition = (element) => {
    window.scrollTo({
      top: element.current.offsetTop,
      behavior: "smooth"
    });
  };

Value of the top property will be the upper edge of scroll position. In this case, we set it to element.current.offsetTop, so top of the scroll position is set to top border of the element.

As we already mentioned, the behavior property specifies the scrolling animation.

Let’s look at the final code:

import { useRef } from "react";
export default function App() {
  const someElement = useRef();
  const setScrollPosition = (element) => {
    window.scrollTo({
      top: element.current.offsetTop,
      behavior: "smooth"
    });
  };
  return (
    <div className="App">
      <button onClick={() => setScrollPosition(someElement)}>
        Set Scroll Position
      </button>
      <p>Element one</p>
      <p>Element Two</p>
      <p ref={someElement}>Element Three</p>
    </div>
  );
}

Button event handler calls setScrollPosition() function for someElement variable, which is linked to third <p> element.

Go to live demo and click the button yourself. It should take you to the third <p> element.

Similarly, you can create refs, link them to different elements (by setting the ref attribute), and create buttons to set scroll position for those elements. Try to do it yourself.

You can use scrollIntoView() method to scroll to a specific element. In another blog post, we explore how to use this method to scroll to bottom of the chat, tables, containers in React.

Set scroll position when component mounts

In the previous example, clicking a button sets scroll position to one of the <p> elements.

Sometimes you want to automatically set scroll position during the lifecycle. For example, when the component first mounts.

In functional components, we use the useEffect() hook to perform side effects when the component first mounts.

In the callback function, we call the setScrollPosition() function and pass it one argument – a ref linked with DOM element you want to set in position.

useEffect(() => {
    setScrollPosition(someElement);
  }, []); 

useEffect() works like componentDidMount() if you pass it second argument of an empty array.

Set scroll position in React (specific coordinates)

In the previous example, we showed you how to set scroll position to specific elements in React.

Alternatively, we can use the scrollTo() method to set scroll position to specific coordinates.

We can pass two arguments to the method:

  • First argument is the number of pixels to scroll from left to right on X axis. In this case, we only do vertical scrolling, so we can set first argument to 0.
  • Second argument is the number of pixels to ‘scroll down’ from upper edge of the page.

Let’s take a look at a very simple example:

export default function App() {
  return (
    <div className="App">
      <button onClick={() => window.scrollTo(0, 1500)}>Scroll somewhere</button>
      <h2 style={{ marginTop: 1500 }}>We're 1500 pixels deep</h2>
    </div>
  );
}

For demonstration, we style the h2 element to have a 1500 pixel-margin on the top.

When users click the button, the event handler will set scroll position to 1500 pixels down. So the h2 element should be visible.

Open live demo on CodeSandbox and click the button yourself.

For scrollTo() method to work, there needs to be enough ‘space’ to scroll down. For example, if you have a scrollTo() method that scrolls down 1500 pixels from the top, but your container is 1000 pixels tall, then nothing will happen.

UX