If current page is site.com/one
and I'm clicking on <Link to='/one'>One</Link>
, it pushing new item to history on every click (but location don't changing). How to prevent that? It's really stupid behaivor.
This issue is also described in issue #470. It may be fixed in the future. In the meanwhile you could use your own link component that does a replaceState
when the location matches with the current one:
link.js
import React from 'react';
import {Route, Link as ReactRouterLink} from 'react-router-dom';
import {createPath} from 'history';
const Link = ({to, replace, ...props}) => (
<Route path={typeof to === 'string' ? to : createPath(to)} exact>
{({match}) => (
<ReactRouterLink {...props} to={to} replace={replace || !!match} />
)}
</Route>
);
Link.propTypes = ReactRouterLink.propTypes;
Link.defaultProps = ReactRouterLink.defaultProps;
export default Link;
app.js
import Link from './link'; // use the custom Link component instead of the react-router Link
const App = () => {
<ul>
<li><Link to={{ pathname: '/one', search: 'foo=bar' }}>one</Link></li>
<li><Link to="/two">two</Link></li>
</ul>
}
The component uses the Route
component to check if the current location matches the location that was defined by the to
prop of the link. If it matches the link will be rendered with the replace
prop set to true
. This makes sure the history item will be replaced instead of added.
Everything else will work the same as the normal Link
component. Just use this component instead of the original Link
and it will work the way you want it.
Working example:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With