Friday, January 31, 2020

ReactJS - You tried to redirect to the same route you're currently on

It's a common problem when you redirect on same route will give a warning like You tried to redirect to the same route you're currently on: /profile/2. It's because of when we define Route we can not define for every parameters like 1, 2, 3 etc. Normally we define our Route like:

<Route path="/profile/:id" component={Profile} />

And this will handle every URL like http://example.com/profile/1, http://example.com/profile/2 etc.
But sometimes when we use Redirect component to redirect to another profile page from current profile page using the below code

return <Redirect to={"/profile/" + this.state.id} push={true} />;

The above warning thrown because our Route is same for all URL like /profile/1 as well as /profile/2.
To avoid this warning we need to define key to our Route like below

<Route path="/profile/:id" render={props => { return <Profile {...props} key={props.match.params.id} />; }} />
Full example is created on CodeSandbox.IO https://codesandbox.io/s/you-tried-to-redirect-to-the-same-route-youre-currently-on-063ot

No comments:

Post a Comment