Skip to content

Scroll to top on route change #132

Description

@m4rocks

How can we make the page scroll back to top on route change? Is there a function we can hook into the Link component? Some kind of option or something

Activity

  1. molefrog commented on Oct 6, 2020

    @molefrog
    Owner

    @notangelmario The solution should probably similar to what they recommend in react-router: https://reactrouter.com/web/guides/scroll-restoration/scroll-to-top

    import { useEffect } from "react";
    import { useLocation } from "wouter";
    
    export default function ScrollToTop() {
      const [ pathname ] = useLocation();
    
      useEffect(() => {
        window.scrollTo(0, 0);
      }, [pathname]);
    
      return null;
    }
  2. m4rocks commented on Oct 6, 2020

    @m4rocks
    Author

    Thank you very much!

  3. xav-ie commented on Nov 9, 2022

    @xav-ie

    Just wanted to note that the solution above is outdated:

    import { useEffect } from "react";
    import { useLocation } from "wouter";
    
    export default function ScrollToTop() {
      const  [ pathname ] = useLocation();
    
      useEffect(() => {
        window.scrollTo(0, 0);
      }, [pathname]);
    
      return null;
    }

    Simply change the curly braces to square brackets and you are set!

  4. molefrog commented on Nov 13, 2022

    @molefrog
    Owner

    I've updated my comment, thanks for spotting the typo @xav-ie

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions