People often want to animate route transitions, which can result in delightful UX when used in moderation. The first instinct might be to use wrap all routes in
TransitionGroup, but that approach requires hacks and falls apart easily when used with trickier components of React Router like
Redirect. You should use
CSSTransition for each route and manage their
in prop on their own.
The main challenge is the exit transition because React Router changes to a new route instantly, so we need to keep the old route around long enough to transition out of it. Fortunately,
children prop also accepts a function, which should not be confused with the
render prop! Unlike the
children function runs whether the route is matched or not. React Router passes the object containing a
match object, which exists if the route matches, otherwise it's
null. This enables us to manage the
in prop of
CSSTransition based on the presence of
Exit transitions will cause the content of routes to linger until they disappear, which might pose some styling challenges. Make sure that routes don't affect each other's layout, for example you can remove them from the flow of the document by using absolute or fixed positioning.
Note: When using React Transition Group with React Router, make sure to avoid using the
Switchcomponent because it only executes the first matching
Route. This would make the exit transition impossible to achieve because the exiting route will no longer match the current URL and the
childrenfunction won't execute.