3
votes

I am using React Router with React Transition Group to animate between routes. I have a problem when I use a <Redirect /> component. The App works, but I get multiple warnings from React Router that reads:

Warning: You tried to redirect to the same route you're currently on: "/"

You can see it happen in this Code Sandbox. Make sure to open the sandbox console and then enter a bad path (like codesandbox.io/abc).

I tried following the example they give in their docs (https://reacttraining.com/react-router/web/example/animated-transitions), but that does not include a Redirect. Is there a better way to use Redirect and Transitions to avoid the warnings?

1
Hmm, removing the location prop on the Switch seems to fix it for me: codesandbox.io/s/w7j1kk8m17 - Chase DeAnda
Hi @ChaseDeAnda unfortunately that breaks the animation. Without the location prop, the current route changes immediately. I slowed down the animation in my original sandbox to better illustrate. codesandbox.io/s/ly9l09m22q Watch the word that animates out when you click. - Steve R
Well maybe that's your problem :) sounds like the location prop isn't updating immediately and is causing multiple redirects to fire off before it updates. - Chase DeAnda
As far as I can tell, location is updating properly. If I log it out in the render, I see render called twice and two logs with the expected location.path, followed by 3 of the above warning. If I remove the TransitionGroup components, I still see those same two logs (and no warnings). Could you suggest a way to test your theory? - Steve R
Hi @FisNaN thanks for the idea, but our real world use case is more complex and contains several redirects. We aren't able to remove them all. I am hoping for a solution that allows us to use transitions and redirects together. - Steve R

1 Answers

6
votes

This issue occurs when a <Redirect> mounts within the animation components.

Instead of wrapping your animation components around <Switch>, wrap the <Route>'s child component. (You may need to use the <Route>'s render prop vs its component prop.)

This approach eliminates the need to pass the location prop to <Switch> -- instead each <CSSTransition/> references location.

See example: https://codesandbox.io/s/nn5r595joj