4 ms·
> So do it for me. I think this will work: Put this wherever you put your reusable functions: `const scrollToTop = () => document.getElementById('root').scro
by charliepark 8y ago
> So do it for me.
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.)
- westurner 8y agoAccidentally downvoted on mobile (and upvoted two others). Thanks for this. "Scroll Restoration" https://reacttraining.com/react-router/web/guides/scroll-restoration https://reacttraining.com/react-router/web/guides/scroll-res...
- jamesknelson 8y agoThis 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-navi/src/View.tsx#L149 https://github.com/frontarm/navi/blob/master/packages/react-... - https://github.com/frontarm/navi/blob/master/packages/react-navi/src/Link.tsx#L259 https://github.com/frontarm/navi/blob/master/packages/react-...