How to use normal anchor links with react-router
The problem with anchor links is that react-router's default is to use the hash in the URL to maintain state. Fortunately, you can swap out the default behaviour for something else, as per the Location documentation. In your case you'd probably want to try out "clean URLs" using the HistoryLocation object, which means react-router won't use the URL hash. Try it out like this:
Router.run(routes, Router.HistoryLocation, function (Handler) { React.render(<Handler/>, document.body);});
React Router Hash Link worked for me. Easy to install and implement:
$ npm install --save react-router-hash-link
In your component.js import it as Link:
import { HashLink as Link } from 'react-router-hash-link';
And instead of using an anchor <a>
, use <Link>
:
<Link to="#faq-1>Question 1</Link><Link to="#faq-2>Question 2</Link><Link to="#faq-3>Question 3</Link>
NOTE: I used HashRouter
instead of Router
import { Link } from 'react-router-dom'
Link using
<Link to='/homepage#faq-1'>Question 1</Link>
Then insert the following code inside your target React component (Homepage):
useEffect(() => { const hash = props.history.location.hash // Check if there is a hash and if an element with that id exists const el = hash && document.getElementById(hash.substr(1)) if (el) { el.scrollIntoView({behavior: "smooth"}) }}, [props.history.location.hash]) // Fires every time hash changes