React Router declarative redirect while preserving a portion of the path

Viewed 235

I've recently had to change a path in my app, but I would like to preserve the validity of old deep links by redirecting them. Here's an example of a changed path:

Original: /foo/users/12345

Updated: /bar/users/12345

I tried to implement this using a redirect:

<Route path='/bar' component={MyComponent} />
<Route path='/foo'>
  <Redirect to='/bar' />
</Route>

However, the latter part of the request is lost in a redirect. So a request to /foo/users/12345 redirects to /bar.

Is there a declarative way to pass the /users/12345 portion of my path along in the redirect?

2 Answers

I was looking into the documentation and I did not find any out of the box solution for this scenario what you were explaining in the question.

Instead of trying to use Redirect I have build a functional component which has been set as the component of the original route. This helps in redirect and can be used for this purpose like below:

<Route path='/foo/:users?/:id?' component={RedirectHelper}/>
<Route path='/bar/:users?/:id?' component={MyComponent}/>

The RedirectHelper looks like this:

const RedirectHelper = (props) => {
  const {history} = props;
  const path = history.location.pathname.replace('/foo', '');
  history.push(`/bar${path}`);
  return null;
}

So technically the RedirectHelper component picks up the value from the history.location.pathname property for the original ~foo/users/12345 URL and builds the new one. At the end it simply redirects to ~bar/users/12345 URL. The validity of the original one has been kept. I have tested out this solution and worked like charm.

Hope this helps!

What if you put a regex in your path

<Route path='/(bar|foo)/' component={MyComponent} />

As answered here

Related