rafgraph / react-router-hash-link

Hash link scroll functionality for React Router
https://react-router-hash-link.rafgraph.dev
MIT License
732 stars 62 forks source link

Using HashLink to scroll to anchor without reloading state #83

Closed douglasrcjames closed 3 years ago

douglasrcjames commented 3 years ago

I am trying to scroll down to an element on a page without losing the information in the current component state, but I can't seem to get it working. I have looked around all over the web and am getting the vibe that this may not be possible with React at all? Which seems like a short sight and maybe I am not looking in the right place. Has anyone had this issue? If so can someone help me solve it?

rafgraph commented 3 years ago

Can you create a minimal reproduction on https://codesandbox.io?

douglasrcjames commented 3 years ago

Check this out: https://codesandbox.io/s/hero-page-with-anchor-hiehx?file=/src/Home.js

rafgraph commented 3 years ago

Thanks for the reproduction. I think your error is in your routes and not related to react-router-hash-link. When you do <Route exact path="/" component={() => <Home />} />, in particular () => <Home />, it will create a new instance of Home on every render. Instead usecomponent={Home}, or use a render prop if you need to write jsx to pass in additional props to Home. Here is it working: https://codesandbox.io/s/hero-page-with-anchor-forked-ysoem?file=/src/routes.js:326-378

douglasrcjames commented 3 years ago

Thanks so much @rafgraph for educating me on this, I am good to go now!