score:18

Accepted answer

Use scrollIntoView to scroll down to the element and React's refs to get the DOM of your component.

Here is a small example that illustrates what you want to do.

var Hello = React.createClass({
  componentDidMount() {
   alert("I will scroll now");

   this.refs.hello.scrollIntoView(); // scroll...
  },

  render: function() {
    return <div ref="hello">Hello {this.props.name}</div>; // reference your component
  }
});

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);

score:0

Unless you need to implement it yourself, you can use react-scroll

Their demo is pretty much what you need.

score:0

you can use react-scroll npm install react-scroll --save

and for information can go to this page https://www.npmjs.com/package/react-scroll

score:2

Using React hooks and no 3rd party packages:

  1. Create a reference using the React hook useRef
import { useRef } from 'react'
const firstItemRef = useRef(null);
  1. Assign the reference to the component you want to scroll to
<Item ref={firstItemRef}>
  1. Use the scrollIntoView method to scroll to the specific Element/Component
<button onClick={() => firstItemRef.current.scrollIntoView()}

score:3

If you are using typescript.

import * as React from 'react';

class Hello extends React.Component<{}> {
  private helloRef = React.createRef<HTMLDivElement>();

  public render() {
    return (
      <div ref={this.helloRef}>Hello</div>
      <button onClick={() => { 
            if (this.helloRef && this.helloRef.current) {
              this.helloRef.current.scrollIntoView();
            } 
          }
      }>Button1</button>
    );
  }
}

score:3

  1. Create a reference using useRef

    const trackButton = useRef();
    
  2. Use scrollIntoView method to scroll to the specific Element/ Component

        trackButton.current.scrollIntoView({ behavior: "smooth", block: "start", inline: "nearest" })
    

score:5

Have you tried using an anchor?

Put an id attribute ('myTarget') to your target component and replace the button with a link (href: '#mytarget').

This does not work with fixed headers, unfortunately.


Related Query

More Query from same tag