While building the next version of RoutePlanGo, I needed a way to animate the page transition when the user navigates to different URLs in the app. RoutePlanGo is built using React and Styled Components and uses React Router for URL handling. This article explains how to use the React Transition Group to implement the page transition animation in the app.
What are we building?
Here’s the example of page transition animation that we are building. This example app has Home page and Details page. When the user goes to details page, it slides in the page and updates the URL. And, when the user goes back, it slides out the details page and slides in the home page for a smooth UI experience.
You can see the code and the example live in here: https://codesandbox.io/s/lrxmv7304l/
1. Setting up the application
For this example, we need to have a react application. You can either use “create-react-app” in your local, or use Code Sandbox in the cloud to setup a simple react application.
Once you have the react app, please install the following modules:
Our demo app has these components: App, starting point and handles route transition between pages, HomePage and DetailsPage to demonstrate the individual pages.
This is the starting point of our app and contains the page transition logic. Since, this component sits at the top level and hosts the individual pages, it makes sense to keep the page transition logic in here.
The App component is a pretty standard React component that uses React Router to navigate to different components based on the matching URL. But the important section in the
CSSTransition. Note, how we wrap the individual routes within these two higher order components.
CSSTransition tracks the underlying components life cycles (mounting and un-mounting) and applies the given class name (in this case,
page), suffixing the current transition state name. We can use this class name to define our transition animations.
For example, when the
HomePage is mounted, it will have the class name
page-enter added to it. Similarly, when it is getting unmounted (for example, when the user navigates to
DetailsPage), it will have
page-exit class name applied and the
DetailsPage will have
page-enter added to its class list.
HomePage contains some text and a link to navigate to
HomePage component is pretty standard React component. But look at how we define the animations and apply the animation on the component level based the transition state class names. Especially,
Also, make sure that your animation timings is less than or equal to the
timeout prop of
CSSTransition component. If it doesn’t match, your animation may look janky. Play around with these timings to have a smooth animation.
The same logic applies to the
DetailsPage component as well. We just need to replace the correct animations. You can view this example and the complete code in live here: https://codesandbox.io/s/lrxmv7304l