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

This allows React to associate the ref with the actual DOM node of the div, which can then be used to scroll to that div when the trigger element is clicked.

Step 2. Set onclick prop on button

Attach the click event handler to the trigger element which will be a button in the below example. We attached the handleClick function as the click event handler to the button element using the onClick attribute. You can also attach the click event handler to other types of elements, such as links or images, depending on your use case.

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

The handleClick will handle the click event on the element that triggers the scroll (e.g., the button). Inside this function, call the scrollIntoView() method on the ref you created earlier, passing in { behavior: 'smooth' } as an option to enable smooth scrolling. This will scroll the div into view with a smooth animation when the trigger element is clicked

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;
This field is required
Your question have been successfully submitted and will be reviewed before published
Please login to ask a question