Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent history.push if location didn't change in react-router4?

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.

like image 854
Daryn K. Avatar asked Jul 29 '18 09:07

Daryn K.


1 Answers

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:

Edit y38j6637k1

like image 152
trixn Avatar answered Oct 18 '22 18:10

trixn