How to Scroll to a List Item in React?

Scrolling mainly refers to the sliding-effect movements on text, images, or graphics across your system’s display vertically, horizontally, or both. During the development of web pages, you can enable scrolling very easily by default for the entire webpage or only those areas where it is needed.

Otherwise, you can hire React developer to develop highly advanced and modern web applications according to your requirement. Today, we will learn how to scroll to an element in ReactJS. However, scrolling React is different from the other frameworks. You can specify an element and then scroll to it automatically or by hitting a button.

How Can You Scroll To A Specific List Item In the React?

The programmers generally use plain JavaScript to scroll to a specific element in React. However, as we mentioned, scrolling to a particular element in React differs from the other frameworks. Here, we will discuss different methods to learn how an individual can scroll to a particular list in React.

Scroll to the Element Using React Refs or References

The easiest and most convenient way to use the ref is to store the reference of that specific element you wish to scroll to. After that, you need to call myref. current. scrollIntoView() so that you can scroll it into the view.

Refs in React contain multiple applications. One of the most popular uses is to reference elements in DOM. You will get easy access to the interface of the elements by referencing the elements. This step is crucial to capture the element you wish to scroll to. Let’s discuss how you can effortlessly create links in the applications to scroll to different web page sections.

Step 1: Creating the React App and Installing the Package

First, you have to create the React application to move forward. Then, you can select ViteJS or anything according to your preference. But, if you are a beginner, you can copy ‘npx create-react-app- my-app-name. After that, you have to install the package that you will need. (react-router-dom).

Step 2: Develop the Section Components

To do this step, first, you need to create three standard components which will further represent each section of the page you will scroll to. Those three components are About, Main, and Usage. Then, in App.js, you must import whatever you want from the ‘react-router-dom’ package. After that, you can easily curate the components, which will further be the sections of your one-page App.

Step3: Properly Assemble the Page Components

The next step that the individual will follow is assembling the page components. Then, the expert will add the components into the app component to quickly set up the components of the react-router.

Step 4: Include the useRef into the App

So, this is the step when the magic will start. In this step, you must import the useRef at the top of the created App,js file. Now, specify the sections you need to scroll to in React. After specifying the areas, you must add three refs to the created App. After that, you need to transfer the refs as props in React in every three section components.

Step 5: Assign the Reference to the Components

In the About, Main, and Usage components, you will get complete access to all three ref props from the before-mentioned step. Then, you can assign the values of those three components to their respective DOM elements.

However, the useRef Hook initialized three props, including aboutRef, mainRef, and usageRef as the null in the App component. After that, with the ref attribute’s help, you can now assign them as values to the DOM element. In such circumstances, developers need to take the mainref prop to assign them to the DOM element in the Main. They will keep doing the same thing to the Usage and About components. So they must remember to assign the proper ref props without making mistakes.

Also Read: Top 10 Most Used React Component Libraries in 2022

Step 6: Produce the Scroll To the Function

Now that every section component contains a reference to easily access the DOM element, it is time to develop a handleScroll function. The web page will scroll to the desired ref in this specific function. An expert will use the window.scrollTo function to indicate that you wish to scroll to the y-coordinates of the DOM element’s offsetTop property.

Step 7: Include the onClick handler in the Link

The final step is to include the handleScroll functionality in the link components. It is a crucial step because when the users tap on the links, it will directly go to the corresponding ref element of the web page. Note that to have the value of ref, you have used ref.current. For instance, mainRef.current is the value of the mainRef.

Example

	
import React from 'react';

const list = [
  {
    id: '1',
    firstname: 'Daniel',
    lastname: 'McConnell',
  },
  {
    id: 'b',
    firstname: 'Olga R',
    lastname: 'Gibson',
  },
  ...
];

const ListItem = () => (
  <ul>
    {list.map(item => {
      return (
        <li
          key={item.id}
        >
          <div>{item.id}</div>
          <div>{item.firstname}</div>
          <div>{item.lastname}</div>
        </li>
      );
    })}
  </ul>
);
export default ListItem;

Because scrolling wouldn’t function without a fake height for each list item, it has one. Let’s check out the execution.

	
import React from 'react';

const list = [ ... ];

const ListItem = () => (
  <ul>
    {list.map(item => {
      const ref = React.createRef();

      const handleClick = () =>
        ref.current.scrollIntoView({
          behavior: 'smooth',
          block: 'start',
        });

      return (
        <li
          key={item.id}
          ref={ref}
        >
          <div>{item.id}</div>
          <div>{item.firstname}</div>
          <div>{item.lastname}</div>
          <button type="button" onClick={handleClick}>
            Scroll Into View
          </button>
        </li>
      );
    })}
  </ul>
);

export default ListItem;

Once more, a ref attribute is added to each item in the list to make the DOM node afterwards accessible. We cannot easily generate the refs for each item within the iteration of the map method, though, because we must work from the outside.

Instead, we must use an additional reduction function to build refs for each list item and store them in an object that is accessible by the list item’s ids (dictionary).

Then, separate from the rendered list itself, we add an additional list of buttons for each list item. Although the handler is the same for all buttons, the parameter is the item’s id. In order to navigate to the list item, the proper ref must be retrieved from the object of refs using the id.

Undeniable Perks of Scroll Effects

The users need to scroll down to navigate the entire website. However, constant scrolling can cause eye strain which may be annoying for the users. So, to combat this, you can hire dedicated React developers from a reputed company to include the scrolling effects on the web page. This way, users do not need to scroll down faster to get to the element they are searching for. Instead, they can click on a particular option to reach their desired areas on the web page more efficiently.

The primary idea of the scrolling effect is to encourage website visitors to scan through multiple parts of a website quickly. Now, they do not have to concentrate on one specific area as they can smoothly access specific portions of the website. However, companies prefer to include the scroll effect on their website to highlight specific areas of the page. It effectively draws website visitors’ attention to the specific content they want their users to look at.

Schedule an interview with React developers

Conclusion

Adding scroll effects to the web page is easy with the correct steps and helpful tools. However, if this is not your cup of tea, consult a trustworthy software development company, Bosc Tech Labs. Their engineers will help you in the mobile app development process to successfully implement the scroll effect using the proper sequence. The company’s expert team has years of experience in this field, so that they will offer adequate guidance. So, without thinking twice, contact the expert team at your convenience.

Frequently Asked Questions (FAQs)

1. How do I ScrollTo the section of the page in React framework?

To scroll an element, click in React: Set a ref prop on the component which you wish to scroll. Set the onClick prop on the other component. However, whenever an element is clicked, it calls the scrollIntoView() method on the ref object.

2. How to develop the scrollable widget?

To include the scrollbar to ScrollView, wrap a scroll view widget in the Scrollbar widget. Hence, you can use this widget as a scroll for the page.

3. How can I scroll horizontally in React JS?

It is a horizontal scrolling menu component for React framework. A menu component has the adaptive width and will set the width for the parent container. However, the item’s width is determined by CSS styles. For navigation, you can use the scrollbar, mouse wheel, drag it by mouse, or the native touch scroll.


Book your appointment now

Request a Quote