4

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?

user51462
  • 1,658
  • 2
  • 13
  • 41
  • It looks like you've found the current open issue. Basically the current implementation doesn't check for the `location` prop and therefore doesn't manage the exiting route correctly. A PR to fix it exists, but unfortunately the main React Router devs appear to be on hiatus while focusing on another project. – jymbob Jan 13 '21 at 21:12
  • @jymbob yes, I wasn't aware of the [issue](https://github.com/ReactTraining/react-router/issues/7297) when I posted here. Someone suggested using [patch-package](https://www.npmjs.com/package/patch-package) to fix it, which worked well for me even though the source is minified. – user51462 Jan 17 '21 at 03:16
  • To patch it, I included `react-router` as a peer dependency in my `package.json` and modified `/node_modules/react-router/index.js` according to the [PR](https://github.com/MeiKatz/react-router/blob/location-prop-for-routes/packages/react-router/index.tsx#L619). I then applied the patch and the transition animation worked as expected. – user51462 Jan 17 '21 at 03:16

0 Answers0