3

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?

Steve R
  • 90
  • 5
  • Hmm, removing the `location` prop on the `Switch` seems to fix it for me: https://codesandbox.io/s/w7j1kk8m17 – Chase DeAnda Mar 22 '18 at 20:27
  • 1
    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. https://codesandbox.io/s/ly9l09m22q Watch the word that animates out when you click. – Steve R Mar 22 '18 at 20:47
  • 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 Mar 22 '18 at 20:52
  • 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 Mar 22 '18 at 21:41
  • Here is my solution https://codesandbox.io/s/o9j8nqpx49 I removed `Redirect` and reorder the routes. It achieves the same behavior, but without redirect the URL. – FisNaN Mar 22 '18 at 22:30
  • 1
    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 Mar 23 '18 at 13:14
  • My point is that you don't have to `redirect` in `switch` component. If you order your router correctly, it normally just works fine. When you try to redirect from certain page to another, you can always call `redirect` inside component. – FisNaN Mar 23 '18 at 21:12

1 Answers1

6

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

lionsdwarf
  • 76
  • 5