Very similar to this angular question: how do I use anchor links for in-page navigation when using react-router?
In other words, how do I implement the following pla
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
if (hash && document.getElementById(hash.substr(1))) {
// Check if there is a hash and if an element with that id exists
document.getElementById(hash.substr(1)).scrollIntoView({behavior: "smooth"})
}
}, [props.history.location.hash]) // Fires every time hash changes
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
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);
});