Animating route transitions with CSSTransitionGroup and React-Router v6 Animating route transitions with CSSTransitionGroup and React-Router v6 reactjs reactjs

Animating route transitions with CSSTransitionGroup and React-Router v6


There has been changes with react-router-v6. Read here and here

To get your animation working, replace Switch with Routes (no need to provide location). Provide element prop to Route. Also install history library.

I have made a working demo using v6. Both entering and leaving animations are working. Compare the code with yours.

Edit react-router-animation-working fix


It seems you want both respective components on screen at the same time; that is, the new component would be animating in while the old is animating out.

This was impossible before v6.0.0-beta.3.

But it is now possible (after v6.0.0-beta.3) thanks to the re-addition of the location prop to the <Routes> component. (release notes for v6.0.0-beta.3)

Your sample code only needs 2 modifications to work for react-router@v6-beta.3, but needs the 3rd modification for the react-router@v6:

  1. <Router> should instead web compatible router, like <BrowserRouter>.
  2. The useLocation() hook must be used in the context of a router component. To fix that, you need a router wrapped in a parent component first, and then you're able to use the hook in any of router's child components.
  3. Replace the children prop with the element prop, otherwise you'll get an error saying all component children of <Routes> must either be a <Route> or <React.Fragment>.

Also – helpful to know for animated routes - "<TransitionGroup> renders a <div> by default" which can sometimes mess with animations. So it's helpful to pass component={null} in props to stop it from doing that.

DEMO: All these changes are available here in this codesandbox:

code-sandbox demo