paint-brush
Setting Scroll Position in Reactby@iraklitch
69,954 reads
69,954 reads

Setting Scroll Position in React

by Irakli TchigladzeJune 21st, 2023
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Learn how to use the **scrollTo()** method to set the scroll position to help users find what they’re looking for. You will also learn to scroll automatically or in response to click and submit events. The method takes one argument: an options object, which is a dictionary that specifies the scroll positions and animation type.
featured image - Setting Scroll Position in React
Irakli Tchigladze HackerNoon profile picture


In this article, you’ll learn how to use the scrollTo() method to set the scroll position to help users find what they’re looking for. You will also learn to scroll automatically or in response to click and submit events.

scrollTo() method

scrollTo() is one of many useful methods available on the window interface. It allows you to scroll down (or across) by a specified number of pixels. For example, scroll 1000 pixels down.


The method takes one argument: an options object, which is a dictionary that specifies the scroll position and its animation type.


The object can have three properties:


  1. top – specifies the number of pixels to scroll down.
  2. left – specifies the number of pixels to scroll across.
  3. behavior – specifies the scrolling animation.


An absolute majority of modern web applications are scrollable only vertically. For this reason, in practice, you will only use top and behavior properties.


Practical use cases

You can use scrollTo() method to scroll down in response to click, submit, and other events.


It’s also possible to use scrollTo() in lifecycle methods (and useEffect() hook) to automatically set scroll position when the component mounts or re-renders.



Set scroll position to specific coordinates

Let’s look at a code example where clicking a button sets the scroll position to a specific section of the page:


<div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <button
        onClick={() => window.scrollTo({ top: 1000, behavior: "smooth" })}
      >
        Learn more
      </button>
      <div style={{ height: 1000 }}></div>
      <p>
        Lorem ipsum…
      </p>
      <div style={{ height: 1000 }}></div>
</div>


shows a page with two heading elements, a button, and two <div> elements that add 1000 pixels of white space.


Clicking the button scrolls 1000 pixels down, so the viewport shows the paragraph text.





Alternatively, you can use lifecycle methods (or the useEffect() hook) to set the scroll position when the component mounts or every time it renders.


export default function App() {
  useEffect(() => window.scrollTo({ top: 1000, behavior: "smooth" }), []);
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
        Learn more
      </button>
      <div style={{ height: 1000 }}></div>
      <p>
        Lorem ipsum…
      </p>
      <div style={{ height: 1000 }}></div>
    </div>
  );
}


The dependency array determines the frequency at which the method is called. Read this guide to learn more about it.


Two ways to set scroll position to a certain element in React

On some occasions, you might need to scroll a certain element into view. To start, you need some way to reference that element in React.


Access DOM elements in React

In plain JavaScript, you might use getElementById() to access DOM elements. Things work differently in React. You need to create a ref to store a reference to the DOM element.


Using the scrollTo() method

To scroll the element into view, set top property to the number of pixels between the element and the top of the page. The value is stored in ref.current.offsetTop property.


function App() {
  const paragraphRef = useRef(null);
  return (
    <div className="App">
      <button
        onClick={() =>
          window.scrollTo({
            top: paragraphRef.current.offsetTop,
            behavior: "smooth"
          })
        }
      >
        Learn more
      </button>
      <p ref={paragraphRef}>
        Lorem Ipsum…
      </p>
    </div>
  );
}



Using the scrollIntoView() method

You can also use the scrollIntoView() method to scroll to an element in React.


There’s an important difference between the two methods. You need to call the scrollIntoView() method on the element itself.


Let’s look at an example:


function App() {
  const paragraphRef = useRef(null);
  return (
    <div>
      <button
        onClick={() =>
          paragraphRef.current.scrollIntoView({
            behavior: "smooth",
            block: "start"
          })
        }
      >
        Scroll to element
      </button>
      <p ref={paragraphRef}>
        Lorem ipsum…
      </p>
    </div>
  );
}


This is arguably a more readable way to scroll to an element in React. You can also use this method to scroll to bottom in React.

Conclusion

Hopefully, learning about scrollTo() method and its many use cases can help you improve the user experience of your app. In this article, we also explored different ways to set a scroll position to a specific element in React.