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.
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>
)
}