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.
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:
<Router>
should instead web compatible router, like<BrowserRouter>
.- 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. - Replace the
children
prop with theelement
prop, otherwise you'll get an error sayingall 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: