Forcing a React-Router <Link> to load a page, even if we're already on that page

In the Route component, specify a random key.

<Route path={YOURPATH} render={(props) => <YourComp {...props} keyProp={someValue} key={randomGen()}/>} />

when react see a different key, they will trigger rerender.


A fix I used to solve my little need around this was to change the location that React-Router looks at. If it sees a location that we're already on (as in your example) it won't do anything, but by using a location object and changing that, rather than using a plain string path, React-Router will "navigate" to the new location, even if the path looks the same.

You can do this by setting a key that's different from the current key (similar to how React's render relies on key) with a state property that allows you to write clear code around what you wanted to do:

render() {
  const linkTarget = {
    pathname: "/page",
    key: uuid(), // we could use Math.random, but that's not guaranteed unique.
    state: {
      applied: true
    }
  };

  return (
    ...
    <Link to={linkTarget}>Page</Link>
    ...
  );
}

Note that (confusingly) you tell the Link which values you need pass as a state object, but the link will pass those values on into the component as props. So don't make the mistake of trying to access this.state in the target component!

We can then check for this in the target component's componentDidUpdate like so:

componentDidUpdate(prevProps, prevState, snapshot) {
  // Check to see if the "applied" flag got changed (NOT just "set")
  if (this.props.location.state.applied && !prevProps.location.state.applied) {
    // Do stuff here 
  }
}

Not a good solution because it forces a full page refresh and throws an error, but you can call forceUpdate() using an onClick handler like:

<Link onClick={this.forceUpdate} to={'/the-page'}>
    Click Me
</Link>

All I can say is it works. I'm stuck in a similar issue myself and hope someone else has a better answer!

React router Link not causing component to update within nested routes

Tags:

React Router