Enable hash / id based routes with react router.
Check the example.
The HashRoute component scrolls to the target element after componentDidMount or on route change when the hash / id matches. The target element is NOT wrapped with <div id='foo' />. Thus the element must render its id properly.
HashRoute is compatible with all means of react-router-dom to navigate (Link, NavLink, etc).
$ npm i react-router-hash-routeGiven the component Foo (Your component MUST render the id prop):
import {Link} from 'react-router-dom'
const Foo = ({id}) => <div id={id}>Foo</div>
const App = () => (
<div>
<nav>
<Link to='/#foo'>Foo</Link>
</nav>
</div>
)
Use HashRoute somewhere inside App. You must provide either render or component prop (similar to Route).
import HashRoute from 'react-router-hash-route'
<HashRoute
id='foo'
render={({id}) => <Foo id={id} />}
/><HashRoute
id='foo'
component={Foo}
/>An optional vertical offset when using fixed headers.
A customizable scroll function with the signature:
const scroll = (node, offset) = {}If you want to have animations etc.
- active route is "/#foo", #foo is in view
- user scrolls
- user clicks link to "/#foo" (e.g. from top nav)
- HashRoute calls
scrollprop (-> #foo scrolls into view)
- with
BrowserRouter:scrollprop is not invoked. Browser "jumps" to #foo. - with
HashRouter:scrollprop is not invoked. Scroll position remains onchanged.
Start watching and building the lib:
$ npm i && npm run devBuild and start the example website with hot-reloading:
$ cd example
$ npm i && npm run dev