CodeNewbie Community 🌱

Sebastian9995
Sebastian9995

Posted on

Scroll to a certain element in React

Modern web applications can be quite overloaded with content. As a web developer, sometimes you want to help users find exactly what they’re looking for. Users don’t like to scroll long pages, especially on phones. You can use something like table of contents to help users navigate long stretches of text, but there is no table of contents for normal page. If you’re building your web application in React, there’s an easy fix – you can simply use scrollIntoView() method.

In this article, we’ll show you how to scroll to a certain element using the scrollIntoView() method. This way, users can skip straight to the part they’re interested in.

The method should be called on a DOM element. In JavaScript, typically we use getElementById() to store a reference to certain element in a variable. React has Virtual DOM, so selecting an element works a little differently. In React, we use refs to store DOM elements in a variable.

There are a number of ways to create refs, but for the sake of simplicity, we’ll use the useRef() hook. It is available in all functional components. Simply import the hook from the core React library, create a variable and set the variable to an instance of a useRef() hook. Then set the ref attribute of the React element to the variable name. Now the variable holds a ref (reference) to the DOM element.

Let’s imagine we have a variable box that holds reference to a

element. You can simply call box.scrollIntoView() and the scroll position will be set to that .

How to use it to improve the user experience

Often times you want to scroll to a certain element on the page as soon as it loads. In React, you can do that by calling ref.scrollIntoView() in lifecycle methods or the useEffect() hook. If you don’t know how to work with the useEffect() hook, read this.

Other times you want to scroll down to element after a certain event. Most frequently this is a click event. You can have buttons for different parts of the page. Users can click these buttons and will be taken immediately to respective elements. This saves a lot of time and will inspire users to come back and use your website again.

Scroll to bottom

Sometimes you want to scroll not to a specific element, but to the bottom of the page. There isn’t a method specifically for scrolling to the bottom. However, you can call scrollIntoView() on the main container of the page and provide it an options object as an argument.

In the options, you can use the block argument to specify which end of the element you want to scroll into view. You can set it to “end” to scroll to the bottom of the element. Because the element wraps around everything on the page, this will also scroll to the bottom of the page.

Top comments (0)