Use anchors with react-router

Don P picture Don P · Oct 27, 2016 · Viewed 60.7k times · Source

How can I use react-router, and have a link navigate to a particular place on a particular page? (e.g. /home-page#section-three)

Details:

I am using react-router in my React app.

I have a site-wide navbar that needs to link to a particular parts of a page, like /home-page#section-three.

So even if you are on say /blog, clicking this link will still load the home page, with section-three scrolled into view. This is exactly how a standard <a href="/home-page#section-three> would work.

Note: The creators of react-router have not given an explicit answer. They say it is in progress, and in the mean time use other people's answers. I'll do my best to keep this question updated with progress & possible solutions until a dominant one emerges.

Research:


How to use normal anchor links with react-router

This question is from 2015 (so 10 years ago in react time). The most upvoted answer says to use HistoryLocation instead of HashLocation. Basically that means store the location in the window history, instead of in the hash fragment.

Bad news is... even using HistoryLocation (what most tutorials and docs say to do in 2016), anchor tags still don't work.


https://github.com/ReactTraining/react-router/issues/394

A thread on ReactTraining about how use anchor links with react-router. This is no confirmed answer. Be careful since most proposed answers are out of date (e.g. using the "hash" prop in <Link>)


Answer

maledr53 picture maledr53 · Aug 20, 2017

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="home-page#section-three">Section three</Link>

NOTE: I used HashRouter instead of Router: