Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router v4 How to <Link> replace only when pathname change

I'm trying to use react-router v4 make menu navigation

Example Code

<BrowserRouter>
  <Link to="/">Home</Link>
  <Link to="/about">About</Link>
</BrowserRouter>
// ...
<Switch>
  <Route exact path="/" component={Home} />
  <Route exact path="/about" component={About} />    
  <Route component={NotFound} />
</Switch>

Problem

This code work correctly, But every time I click on a Link. BrowserHistory alway have push new location That make browser back/forward not properly.

Ex. When I click on a Home for 5 times it should be just push 1 time and replace for 4 times

Problem only when using BrowserRouter (HashRouter works properly)

Ex: BrowserRouter
Ex: HashRouter

I want to do Link replace only when path not change.
Is possible? Is there a simple way to do?

like image 656
jeanzuck Avatar asked Feb 15 '26 04:02

jeanzuck


1 Answers

If you want the link to replace the current entry in the history stack you should use the replace attribute on the <Link /> component.

Check this for more info: https://reacttraining.com/react-router/web/api/Link/replace-bool

Check this discussion on github: https://github.com/ReactTraining/react-router/issues/3776

like image 100
Moe Avatar answered Feb 16 '26 18:02

Moe