Re:React Router v5
by jamesknelson on Thursday March 21, 2019 @09:47AM
(#19452252)
This is a nice and simple solution! Just keep in mind that it'll interact badly with the browser's scroll-to-hash functionality.
A full solution is a little more tricky, and probably involves code on multiple components:
- You'll need something to scroll to the top or the current hash on load - You'll also need code on <Link> components to check if they link to the current URL/hash, and if they're pointing to the current hash, you'll need to scroll to it on click.
Here's some relevant scroll management code from Navi's components:
- https://github.com/frontarm/navi/blob/master/packages/react-...
- https://github.com/frontarm/navi/blob/master/packages/react-...
Accidentally downvoted on mobile (and upvoted two others). Thanks for this.
"Scroll Restoration" https://reacttraining.com/react-router/web/guides/scroll-res...
I think this will work:
Put this wherever you put your reusable functions:
`const scrollToTop = () => document.getElementById('root').scrollIntoView();`
And put this in the components / functions you want the scrollToTop effect to work on:
`useEffect(() => { scrollToTop() }, []);`
And put this in your CSS:
`html { scroll-behavior: smooth }`
(Edit to add: Not saying React Router is something you should / shouldn’t use. Just wanted to share that code in case it helps unblock anyone.)