3

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?

Eric HB
  • 867
  • 6
  • 17
  • Why not https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo after the push? – apokryfos Nov 20 '20 at 00:46
  • 1
    I'm assuming you're using react-router. [react-router scroll to top on every transition](https://stackoverflow.com/questions/36904185/react-router-scroll-to-top-on-every-transition) – Guy Incognito Nov 20 '20 at 00:52

1 Answers1

2

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

Tony Drummond
  • 365
  • 2
  • 10
  • Thanks for this! The other linked questions used classes instead of functional components, so I think this is helpful and adds value, although the question may still be duplicate... – Eric HB Nov 20 '20 at 18:28
  • Although this seems to override my routes somehow, maybe it's my setup but when I use Link from react-router-dom, it seems to send me back to the main page after quickly switching to the linked page – Eric HB Nov 20 '20 at 18:33
  • @EricHB - we'd have to see your code. However, I can't see how anything relating to this would be causing that issue. I am using Link in my app just fine. Actually, both apps I'm using this same exact code in work fine. – Tony Drummond Nov 20 '20 at 18:46