How to Scroll An Element In React

How to Scroll to An Element In React?

Today we will learn about how to scroll an element in reactJS. scroll to an element in React is a little different than other frameworks. You can refer to an element and scroll to it, either automatically or by clicking a button.

Scrolling is defined as sliding-effect movement on images, text, or graphics across the computer display screen horizontally, vertically, or both. When developing web pages, you can enable scrolling by default for the complete webpage or only the areas where it is required. Else, you have an option to hire ReactJS developers for the creating highly progressive web applications as per your requirement.

the Element.scrollIntoView() method provided by HTML element interface and React refs (short for references), which can be created either using useRef() hook (for functional components), or createRef() method (for class components). If you don’t know much about hooks, checkout the best practices of hooks for better use of React hooks.

Scroll to an Element With the Element.scrollIntoView() Method in React:

This Method accept one argument.

The scrollIntoView() method scrolls an element into the visible area of the browser window.

Syntex:

element.scrollIntoView(align)

The element.scrollIntoView() accepts a boolean value or an object:

element.scrollIntoView(alignToTop);

  • The alignToTop is Boolean value.

element.scrollIntoView(options);

  • Options have main 3 properties

1. block
2. behavior
3. inline

1. Block: This Property define vertical alignment. It accept 4 value:

  • start
  • center
  • end
  • nearest

By default set value is started.

2. Behavior: behavior property defines the transition animation. It accepts 2 values:

  • auto
  • smooth

By default set value is auto.

3. Inline: property defines horizontal alignment. It accepts 4 values:

  • start
  • center
  • end
  • nearest

By default set value is nearest.

Example:

var element = document.getElementById("box");
element.scrollIntoView();
element.scrollIntoView(false);
element.scrollIntoView({block: "end"});
element.scrollIntoView({behavior:"smooth", block: "end", inline:"nearest"});

Scroll to an Element With the React Refs (References):

The most simple way is to use ref to store the reference of the element that you want to scroll to. And call myRef.current.scrollIntoView() to scroll it into the view.

Refs in React have many different applications. One of the most common uses is to reference elements in the DOM. By referencing the element, you also gain access element’s interface. This is essential to capture the element to which we want to scroll.

useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). useRef() is useful for more than the ref attribute.

const divRef = useRef(null);

In Functional Component:

import React, { useRef } from 'react';

const App = () => {
  const scollToRef = useRef();

  return (
    <div className="container">
      <button onClick={() => scollToRef.current.scrollIntoView()}>
        Scroll
      </button>
      <div ref={scollToRef}>scroll Me</div>
    </div>
  );
};

export default App;

In Class Component:

class TestComponent extends Component {
  constructor(props) {
    super(props);
    this.testRef = React.createRef();
  }
  scrollToElement = () => this.testRef.current.scrollIntoView();
  
  render() {
    return <div ref={this.testRef}>Element you want in view</div>;
  }
}

Scroll to an Exact Location:

In this part react provide inbuilt function scrollTo.

Syntex:

scrollTo(x, y)

above function use in native platforms.

Example:

const ref = useAnimatedRef();
ref.current.scrollTo({ x, y });

useAnimatedRef():- The useAnimatedRef which is a Reanimated’s extension of a standard React’s ref.

x-cord:- horizontal axis of the element that you want displayed in the upper left.

y-cord:- vertical axis of the element that you want displayed in the upper left.

React Hash Scroll:

React Hash Scroll is a popular library used in many React projects. It aims to be the simplest way to implement hash routing.

import { HashScroll } from "react-hash-scroll";

Simply Add this library in your code.

Example:

import React from "react";
import { Link } from "react-router-dom";
import { HashScroll } from "react-hash-scroll";

const HashScrollPage = () => {
  return (
    <main className="page">
      <nav>
        <ul>
          <li>
            <Link to="/hash-scroll#hash-section-1">Go To Section 1</Link>
          </li>
          <li>
            <Link to="/hash-scroll#hash-section-2">Go To Section 2</Link>
          </li>
        </ul>
      </nav>
      <article>
        <HashScroll hash="#hash-section-1">
          <section>Section 1</section>
        </HashScroll>
        <HashScroll hash="#hash-section-2">
          <section>Section 2</section>
        </HashScroll>
      </article>
    </main>
  );
};

export default HashScrollPage;

Schedule an interview with React developers

Conclusion:

So, in this article, we looked at how to scroll an element. We show in the article the use of multiple methods and properties. Also learn the new library. We can use it directly in the Outer Code.

Thanks for reading our article. Hope you enjoyed the reading!!!


Hire React Developer Today!

Request a Quote