Let’s Create a React CSS Transitions|Animations (React Transition Group)

Video Tutorial

Getting Started

CSS Transitions are very important especially if you ever wanted to create a fully well designed React application including some nasty animations between components or even pages of your app, The React Transition Group module allows you to render components with specific CSS transitions to be applied whenever the component is mounted or unmounted from the DOM.

The reason we need to use react transition group for applying custom CSS transitions cause react works by mounting (rendering) and unmounting (removing) components from the DOM every time the state gets updated while the regular (standard) CSS transitions (animations) can only be applied to components (elements) that are always living in the DOM.

Please make sure to learn the basics of React first from Here.

Also, check the last tutorial on the React series of building a modern login form since we are going to use this login/register form on today’s tutorial and try to add some transitions to it.

I really recommend you get some CSS transition working experience before jumping right into the tutorial cause we will be using a lot to make the animation possible.

The Full Project of The Login/Register Form is available on Github in case you need to grab the source code.

Now let’s install the React transition group module for working with the transitions.

npm install react-transition-group --save

We need to add a new folder containing all of our transitions we will be creating and each transition will be held on a single react component file to make it easier for reusing the transition couple of times.

under src/ create a transitions/ folder and add fadeTransition.jsx file which is going to be responsible for applying a fading transition on a specific component or element(s).

Fade Transition

You can create any type of transition you would like to but for the seek of simplicity we will go with the fade transition which is basically fade-in & fade-out component animation which is done by manipulating the CSS opacity property.

There are a lot of ways to apply transitions to a specific component so, what I believe is the simplest way to apply transition is by creating a React component for each transition which takes the desired (target) children (elements/components) you want to have the transition on as a children and return back a new children with the CSS Transition style applied.

Let’s create the fade transition component.

import React from "react";
//Import Transition from the /Transition subfolder 
import Transition from "react-transition-group/Transition";
//Export Default FadeTransition Class
export default class FadeTransition extends React.Component {
  constructor(props) {
    super(props);
    //Default Style (Static CSS Style to be applyed)
    this.defaultStyle = {
      transitionProperty: "opacity",
      transition: `${this.props.duration}ms ease-in-out`
    };
    //Transition To Apply (the actual css transition to apply)
    //there are 4 states on the transition (entering, entered, exiting, exited).
    this.transitionStyle = {
      entering: {
        opacity: "0"
      },
      entered: {
        opacity: "1",
        transitionDelay: "700ms",
      },
      exiting: {
        opacity: "0"
      },
      exited: {
        opacity: "0"
      }
    };
    //Since we are doing fade so it is just about opacity (0 and 1 values).
  }

The main part you need to keep an eye on is the transition style object which is a nested object of the available transition states, these states are going to be provided by the react transition group so let’s say a component has mounted on the DOM the transition state will go first on entering then after a specific duration of time (in seconds or milliseconds) it change to entered, and does the same thing when it gets unmounted from the DOM it goes through the (exiting then exited) states and of course it applies the defined CSS style on the component on each state it goes through and this is how the transition can be applied smoothly.

We add the transition delay to delay between moving from one transition to the other works pretty well if you have two or more components needs the transition to be applied so each transition cycle would wait a short amount of time before starting so you can easily toggle between the two.

For the default style, we simply specify the style gets applied by default on the target element or component and most of the time you want to put the transition property, the transition duration, and the timing function.

On this line:

transition: `${this.props.duration}ms ease-in-out`

We are using compiled string literals which is basically equivalent to concatenating a variable and a string.

Now we need to render and apply the transition of the current state to children.

render() {
  return (
    <Transition in={this.props.isOpen} timeout={this.props.duration}>
      {state => {
        //State is exited then we return render nothing.
        if (state == "exited") return null;
        //Loop on all children and clone new child with a new style applied (transition style).
        return React.Children.map(this.props.children, child => {
          return React.cloneElement(child, {
            style: Object.assign(
              {},
              this.defaultStyle,
              this.transitionStyle[state]
            )
          });
        });
      }}
    </Transition>
  );
}

The transition component takes two properties, the in property which is responsible for rendering the children (True or False) and the timeout which determines the duration of the transition (in milliseconds) and we simply use our properties for it.

it takes a callback as a child which provide you with the current being rendered state so you would know which transition to apply depending on the state you have already defined on the transition style object.

We also use the react children map function in order to loop on the collection of children we receive from the props and we access each child, notice that we are not using the map function in the children collection since it’s not an array or a map so we would have to use the React provided map method, it basically returns a callback with the child and it’s index and finally we clone a new element from the child (Cloning basically mean creating a new element with the current element’s props merged with the provided props, in this case, it is going to be the style object) and since it returned so it will get rendered.

Object.assing({}, this.defaultStyle, this.transitionStyle[state]);

the assign method returns a new object merged with the provided sources which are the default style and the transition style gets extracted by the current state.

And that’s all for the applying transitions to the target children if you still can’t quite figure out how the above code works you still can just copy and use the code but only change the transitionStyle to your own, and everything should work.

Applying Transitions

Applying the above transition or any other transition you create using the structure we have used on this tutorial is as simple as rendering a React component and providing it with the target elements or components.

import FadeTransition from "../src/transitions/fadeTransition";
...
{/*Applying to Login Box*/}
<FadeTransition isOpen={this.state.isLoginOpen} duration={500}>
   <div className="box-container">
      <LoginBox />
   </div>
</FadeTransition>
{/*Applying to Register Box*/}
<FadeTransition isOpen={this.state.isRegisterOpen} duration={500}>
   <div className="box-container">
      <RegisterBox />
   </div>
</FadeTransition>
...

You remove the && operators which are used to determine whether or not to render the target element but in this case, we provide it with the isOpen property which takes true or false and the duration of the transition and that is it.

Try to open the login box and toggle between the login and register boxes you should be able to see them transitioning with a very smooth fade animation.

What’s Next

Make sure to try to make more advanced transition example using the above structure so you would learn to have a bit better control on those transitions also you can use the power the CSS transitions property to make much smoother and nice animations.

No Comments Yet