0

I have something like this:

<Route path="/route/:param" component={DealContainer} />

Then while the component is mounted I am doing a client side redirect:

componentWillMount() {
  if (this.props.match.params.param != 'desired_one') {
    this.props.history.push('/route/desired_one');

Despite the fact that the url changes the component is not remounted... Any ideas?

Boti
  • 2,871
  • 1
  • 25
  • 47

1 Answers1

2

You should resolve this issue by using the Redirect component inside "react-router-dom" package

<Route exact path="/route" component={DealContainer} />
<Route
  exact
  path="/route/desired"
  render={() => <Redirect to="/route/desiredRedirectLocation" />}
/>
<Route path="/route/:param" component={DealContainer} />

This implementation should:

  • Match the exact base route correctly, without matching any props. Lets say that you want to show a list of items (e.g. /products)
  • Match the desired item to be redirected (e.g. products/car) and redirect it to the desired location, let's say products/horse
  • Match any other case that you don't want to redirect /products/:id and correctly take the prop you are after inside the match object.

Explanation

The problem with history.push, is that React will figure out you are using the same component, and will only update the differences, without actually re-mounting the component, which is already mounted.

My example with redirect on the other hand, will intercept the route you want to redirect without mounting the component first, so component will be mounted after the redirect happened, correctly executing the action that you need.

Vlatko Vlahek
  • 1,436
  • 11
  • 18