Scroll to a div on click in React JS

How to scroll to a div on click using React JS

Posted by Raquel Crist on August 24, 2022

Scroll to a div on click in React JS

How to scroll to a div on click using React JS

Posted by Raquel Crist on August 24, 2022

In order to scroll to a div on click in react:

Step 1. Set a ref prop on the div element

Step 2. Set onclick prop on button

Step 3. Once the button is clicked use scrollIntoView() to move to the div with ref

Here is an example below:

class App extends Component {
    constructor(props) {
        super(props);
        this.ref = React.createRef();
    }

    handleClick = () => {
        this.ref.current.scrollIntoView({
            behavior: 'smooth'
        });
    };

    render() {

        return (
            <div>
                <button className="btn btn-primary" onClick={this.handleClick}>got to point</button>

                <div style={{height: '700px'}} />

                <div ref={this.ref}>the point is here</div>

                <div style={{height: '300px'}} />
            </div>
        )
    }
}
export default App;