Languages
[Edit]
EN

React - scroll to element

0 points
Created by:
Rubi-Reyna
677

In this article, we would like to show you how to scroll to a specific element in React.

In the example below, we use the useRef hook with which we can easily obtain a handle to a DOM element we want to scroll to.
Then, after clicking on the button, we call the scrollIntoView() method.

Note:

scrollIntoView() method called without any arguments avoid animations scrolling immediately to indicated element.

Passing arguments to this method is new functionality and may not be compatible with all browsers.

Also note that the mechanism of the method is complex - clicking the button will not scroll only the nested page that the button is on, but also the parent pages.

// ONLINE-RUNNER:browser;

// Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';

const App = () => {
  const scrollRef = React.useRef(null)
  const scrollTo = () => scrollRef.current.scrollIntoView({ behavior: 'smooth' });

  return (
    <>
      <button onClick={scrollTo}> 
        Click this button to scroll 
      </button>
      <div style={{ height: '800px' }} />
      <div ref={scrollRef}>Element to scroll to</div>
      <div style={{ height: '800px' }} />
    </>
  )
}

const root = document.querySelector('#root');
ReactDOM.render(<App />, root);

Alternative titles

  1. React - scroll to a specific element
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

ReactJS

React - scroll to an element
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join