Using React Transition Group to animate your components

#145

React - React Transition Group

February 21, 2020

alt text

Hope you're having a nice Friday guys 😁👌
React Transition Group is an awesome reactJS library that helps us animate components that are entering or leaving the page. Even though it does not create the animation itself for us, this gives access to the elements while they are transitioning.

To use it, we first install it by doing 'npm install react-transition-group --save'. Then we'll create an 'App' Component and in that file we will import 'CSSTransition' from 'react-transition-group'. On our Component, we start by creating a state property just to toggle the content and a function that will do the toggling.

alt text

Next, we return a button to toggle the content and a div for our content. Here we'll have each content wrapped in a 'CSSTransition' component. We need to pass it some props. First we pass 'in' with the condition for it to be shown, next the 'timeout' with amount of milliseconds we want for the transition, then we pass 'classNames' with whatever name we want for the classes that will be used for the animation and finally we pass 'unmountOnExit' to remove this Component when done.

alt text

Now we just need some CSS to get this done. We start by applying some basic styles to our content elements and then we use the 'fade' classes that will be generated by React Transition Group. More specifically, this will give us a class '-enter' when the Component enters, a class '-enter-active' when it's done entering, a class '-exit' when it starts leaving, and a class 'exit-active' when it's done leaving . We just need to use this four classes now to create the animation using opacity and transform.

Hope you liked this tip, see you soon! 🤓✌