You can select a DOM element and update the scrollable element's (e.g. body)
scrollTop position manually, or using the
scrollTo method to match the DOM element's
top position on the screen. However, there's an easier way...
Using scrollIntoView function
The simplest way to scroll to an element in React is by calling the
scrollIntoView function on the element. However, you first need to get the DOM element ref from
useRef or select it from the DOM directly.
Here's how you might scroll to another section when clicking a button:
Here's what it looks like:
scrollIntoView method accepts optional parameters to control the scroll animation and where to focus on the element.
Real quick - would you like to master Web Development? If so, be sure to check out my recommended platform to learn coding online:
Scroll to a new element in React
Because we require a referent to a DOM element to scroll it into view, we may run into problems when the DOM element is created in response to state changes in React.
An example of this problem is a list, where we want to scroll to the last element in the list after a new one is added, but the list is rendered based on an array in the state.
You can use the flushSync method from
react-dom to update the DOM immediately after the component state is updated. Here's how it can be used:
Here's what the result looks like:
Scroll to element only if needed
scrollIntoView method will scroll even if the element is already visible on the screen. You may not want it to do anything in that case. There is an alternative method with the same options called
scrollIntoViewIfNeeded option is still experimental without good support on Firefox. To achieve complete support, you can use a ponyfill.
scrollIntoView (and also
behavior: smooth you're leaving it up to the browser to control the animation. This means smooth scrolling may not work with some browser or OS settings.
I've noticed, that if I uncheck the "Animate controls and elements in windows" box in my Windows Performance Options, the smooth scrolling stops working across all browsers.
To gain more control you may use a 3rd party scroll-into-view library, which will also give you additional options to fine-tune the scroll behavior.
scrollIntoView method. However, it doesn't offer much fine-grained control and depends on browser and OS settings.
If you're willing to put a little more effort, you can use a 3rd party library that allows you to tweak the settings to your liking. It works by manually updating the
scrollTop position, so it's unaffected by the environment settings.
Hey, if you're serious about learning React, I highly recommend the courses on educative.io - it's my favorite platform for learning to code.
Here's a course on React that will teach you how to build something more than another to-do app (finally, am I right?):