props.history.push('/') does not go to top of page (need functional component)

Viewed 704

I am building a website with React and the user clicks a button to register. In the callback on that button, I use props.history.push('/') to redirect to the main page.

In the registration page, they have to scroll down slightly and where they are on the page carries over into the main page. Is there another way to redirect that goes to the top of the page?

1 Answers

Solution below with example showing how to use it. This will make the window scroll to the top automatically throughout your entire app. Credit unknown - I got it from somewhere on here.

React component - ScrollToTop:

import { useEffect } from "react";
import { withRouter } from "react-router-dom";

function ScrollToTop({ history }) {
    useEffect(() => {
        const unlisten = history.listen(() => {
            window.scrollTo(0, 0);
        });
        return () => {
            unlisten();
        };
    }, [history]);

    return null;
}

export default withRouter(ScrollToTop);

Photo showing how I'm using it in my app: enter image description here

Related