React Router v6.0.0-beta0 - Animating route transitions with TransitionGroup and CSSTransition

1.6k Views Asked by At

My app has two routes: Step1 and Step2 and a Next button that takes you from Step1 to Step2. I would like to animate the transition between Step1 and Step2 so that when the user clicks Next, Step2 slides into view from the right while Step1 slides out of view to the left.

This works in React Router v5.2.0 (v5.2 demo), but not in v6.0.0-beta0 (v6 demo).

  • In the v5.2 demo, when you click Next, you can see that Step1 transitions out and Step2 transitions in as expected.
  • However, in the v6 demo, when you click Next, Step1 is immediately replaced by Step2 and the exit transition is applied to it, so that Step2 appears to be entering and exiting at the same time.

I think this might be due to the <Routes> component (which is the v6 equivalent of <Switch>, see migration guide here).

According to the v5 docs (line 48), you must pass the location object to <Switch> so that "it can match the old location as it animates out". <Switch> then uses this object instead of context.location to match the path (see line 19):

const location = this.props.location || context.location;

...whereas <Routes> just reads location from the context (see line 532):

let location = useLocation() as Location;

I think this explains the behaviour in the v6 demo - you can see that the exiting route is re-rendered from <Step1> to <Step2> as it is exiting, is this correct? How can I prevent this re-render?

0

There are 0 best solutions below