Pol
Pol

Reputation: 1351

React-Static scroll to top on page change

Is there a way to scroll to the top when the page change with react-static ? I'm using @reach/router which is include by default with react-static.

I've already tried this :

<Router onChange={window.scrollTo(0,0)}>
   <Routes path="*"/>
</Router>

ans this (from this issue)

<Router history={history} autoScrollToTop={true}>
   <Routes path="*"/>
</Router>

but both did not work.

The last solution was mentionned in the react-static doc but seems to be deprecate since it is not longer in the doc.

Upvotes: 0

Views: 622

Answers (2)

Pol
Pol

Reputation: 1351

You need to create a new component Scrolltotop.js

import { useEffect } from 'react'
import { useLocation } from '@reach/router'

export default function Scrolltotop () {
  const { pathname } = useLocation()

  useEffect(() => {
    window.scrollTo(0, 0)
  }, [pathname])

  return null
}

and import it to App.js

import Scrolltotop from './components/Scrolltotop'

and add it to the App function :

function App () {
  return (
    <Root>
      <Scrolltotop/>
      <Router>
        <Routes path="*"/>
      </Router>
    </Root>
  )
}

Upvotes: 3

Taylor Osbourne
Taylor Osbourne

Reputation: 11

try having a component that handles the scroll for you and lives above your app component.

Usage:

import ManageScroll from './ManageScroll';
ReactDOM.render(<Fragment><ManageScroll/><App/></Fragment>, node);

ManageScroll.js:

import React from "react";
import { Location } from "@reach/router";

let scrollPositions = {};

class ManageScrollImpl extends React.Component {
  componentDidMount() {
    try {
      // session storage will throw for a few reasons
      // - user settings
      // - in-cognito/private browsing
      // - who knows...
      let storage = JSON.parse(sessionStorage.getItem("scrollPositions"));
      if (storage) {
        scrollPositions = JSON.parse(storage) || {};
        let { key } = this.props.location;
        if (scrollPositions[key]) {
          window.scrollTo(0, scrollPositions[key]);
        }
      }
    } catch (e) {}

    window.addEventListener("scroll", this.listener);
  }

  componentWillUnmount() {
    window.removeEventListener("scroll", this.listener);
  }

  componentDidUpdate() {
    const { key } = this.props.location;
    if (!scrollPositions[key]) {
      // never seen this location before
      window.scrollTo(0, 0);
    } else {
      // seen it
      window.scrollTo(0, scrollPositions[key]);
    }
  }

  listener = () => {
    scrollPositions[this.props.location.key] = window.scrollY;
    try {
      sessionStorage.setItem(
        "scrollPositions",
        JSON.stringify(scrollPositions)
      );
    } catch (e) {}
  };

  render() {
    return null;
  }
}

export default () => (
  <Location>
    {({ location }) => <ManageScrollImpl location={location} />}
  </Location>
);

check out this gist for further info https://gist.github.com/ryanflorence/39a37a85254159fd7a5ca54027e175dc

hope this helps!

Upvotes: 0

Related Questions