Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use normal anchor links with react-router

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 plain HTML when using react-router?

<a href="#faq-1">Question 1</a> <a href="#faq-2">Question 2</a> <a href="#faq-3">Question 3</a>  <h3 id="faq-1">Question 1</h3> <h3 id="faq-2">Question 2</h3> <h3 id="fa1-3">Question 3</h3> 

Currently I intercept clicks on such links, and scroll to the anchor position. This isn't satisfactory, because it means it's impossible to link directly to some section of a page.

like image 973
starwed Avatar asked Mar 06 '15 07:03

starwed


People also ask

Can I use anchor tags in React?

In React, relative URLs should always be handled by the link tag provided by the React Router, and pure anchor tags should only be used for absolute paths. You can also think of relative URLs as in-app navigation, for example navigating to a particular route of the app and absolute paths as external links.

How do I use React Router without changing URL?

To use React Router without changing the URL, we can use the MemoryRouter component. to import the MemoryRouter component and then wrap it around App to let us navigate with React Router without changing URLs.


2 Answers

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); }); 
like image 79
Colin Ramsay Avatar answered Oct 06 '22 07:10

Colin Ramsay


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

like image 24
maledr53 Avatar answered Oct 06 '22 07:10

maledr53