Improving UI with React Transition Group

Learn via video courses
Topics Covered

Overview

React Transition Group, or react-transition-group, is a react library that enables us to transition elements or components in and out of the DOM more efficiently. It provides us with three different types of components, using which we can mount and unmount components in an easy-to-understand manner. We can set different properties on various stages through which a component goes, and then using the timeout attribute given by these components, we can visualize how a component gets transferred from one state to another.

Introduction to React Transition Group

As stated by its developers, React Transition Group is a,

A set of components for managing component states (including mounting and unmounting) over time, specifically designed with animation in mind.

In simple words, React Transition Group lets us transition the components in and out of the DOM in a more efficient and visually understandable way. Which, in turn, means it is a more straightforward approach to transitions and animations.

However, I would like to mention that react-transition-group is not an animation library, unlike react-motion, react-spring, etc. The animations implemented using react-transition-group are pure CSS Transitions. They involve minimal or almost no use of any JavaScript property.

How to Install React-transition-group?

Let’s now see how we can install it. We can start by initializing a new react app in our system. To do so, open the system’s terminal in the appropriate folder and execute the following command.

This will set up a basic structure of a react application, and once this is done, we would be needing to add the react-transition-group package in our app. So let's install that as well.

Components of React Transition Group

Primarily React Transition Group provides three different types of components to choose from, depending upon what the user needs, they can proceed with that.

1. Transition

The first React Transition Group component that we will discuss is Transition. The Transition component lets us describe transitions in a specific component from one state to another. It can most commonly be used to demonstrate the mounting and unmounting of a component.

The Transition Component has four primary states which we can utilize to implement it. But first, let's see an example to understand it better.

App.js file:

Output:

components-of-react-transition-group

Explanation:

Inside App.js, we have a Transition component that accepts a prop named in, which when set to true, will make the component initiate into the entering state till the specified timeout duration. And after that, the component will enter into the entered state.

As soon as the in prop gets set to false, the component will get initiated into the exiting state until the specified duration. And after the timeout ends, it will attain the exited state.

Initially, we have set the inProp to be true, which we can see in the output make the text Hello world blue, but as soon as we click on the Start Transition button, the transitionHandler() function gets called and inverts the value of the inProp state, which makes the component enter into exiting state, and after 1000ms it gets exit and thus the color change.

This is a simple example demonstrating the use of the Transition component from React Component Group.

2. CSSTransition

The CSSTransition component is an extension of the standard Transition component. And as it is built on top of that, therefore it inherits all of its properties. It provides six different classNames based on the className we would assign to our component, each denoting different stages like

  • providedClassname-enter: Component's mounting initiated
  • providedClassname-enter-active: Component's mounting in process
  • providedClassname-enter-done: Component mounted
  • providedClassname-exit: Component's unmounting initiated
  • providedClassname-exit-active: Component's unmounting in process
  • providedClassname-exit-done: Component unmounted

Let's have a look at an example to understand it better.

App.js file:

CSS file:

Output:

components-of-react-transition-group-2

Explanation:

Here in App.js, we are rendering the CSSTransition component provided by the react-transition-group library, it accepts a prop named in which by default we are setting here as false to toggle between mounting and unmounting of the inside div of the CSSTransition component. The timeout specified here is 1000ms, and it accepts an additional parameter named classNames.

Whatever className we specify here, the CSSTransition component provides us with six different variations of it, each denoting the six stages of a component's lifecycle here, which we discussed above. And we have styled those classes in the attached CSS file to demonstrate how the animation works. Below that, we have a button that triggers the transitionHandler() function, which inverts the value of the isVisible state variable when clicked.

3. TransitionGroup

As the name suggests, the TransitionGroup component manages a set of Transition and SwitchTransition components. It behaves like a parent group which can be used to manage the mounting and unmounting states of its child components.

I would like to mention that the TransitionGroup component does not define any animation behavior of its own; instead, it only manages its children components. Meaning how a component animates is still up to that specific component's behavior.

Let's have a look at an example.

App.js file:

CSS File:

Output:

components-of-react-transition-group-3

Explanation:

Here in App.js, we are initializing a state array variable named tasks, which stores certain tasks and their ids. Then after we have a handleTask function which takes a task object as input and iterates over the original tasks array state using the filter() method. The filter() method is a built-in JavaScript method used to filter out the matched element and return the remaining array. So the handleTask() method here takes a task as input and removes that specific task from the original tasks array, and returns the result, which then the tasks array gets updated with the new set of values.

Inside the JSX, we have the TransitionGroup component, in which we are iterating over the tasks array and rendering each task as a child of the CSSTransition component. Along with the task name, we have a button that calls the handleTask function when clicked, which removes that specified task, and we can see that in the animation.

Animation Add-ons in React Transition Group

React CSSTransition Group: High-Level API

React CSSTransitionGroup is a high-level API based on React Transition Group. Let's understand this with the help of an example.

App.js file:

CSS file:

Output:

animation-add-ons-in-react-transition-group

Explanation:

Here in App.js, we are having a state array named items, which is initially set to empty. Then, we have a handleAdd() method, which is responsible for adding new items to the items array by taking a prompt from the user. Finally, we also have a handleRemove() function, which removes elements from the items array.

Inside the JSX, we have a button, that when clicked, calls the handleAdd() function to add new items. After that, we have the CSSTransition component, which is rendering a div inside it. The div is iterating over the tasks array and is displaying all the elements inside it. The internal div is also handling the deletion of elements call when clicked by calling the handleRemove() function.

We can see when new elements are added how the color of the text changes, indicating various stages through which they are getting passed.

React TransitionGroup: Low-Level API

As per React Docs, React Transition Group is the basis for animations. And when children's elements or components are declaratively added or removed inside it, special lifecycles methods are called on them. For example :

componentWillAppear(callback):

Called at the same time as componentDidMount() for components that are initially mounted in a TransitionGroup. It will block other animations from occurring until the callback is called, only called at the initial render of a TransitionGroup.

componentDidAppear():

Called after the callback function, which was passed to the above componentWillAppear() gets called.

componentWillEnter(callback):

Called at the same time as componentDidMount() for components added to an existing TransitionGroup. It will block other animations from occurring until the callback is called and will not be called at the initial render of a TransitionGroup.

componentDidEnter():

Called after the callback function, passed to the above componentWillEnter gets called.

componentWillLeave(callback):

Called when the child has been removed from the ReactTransitionGroup. The child has been removed, but ReactTransitionGroup will keep it in the DOM until callback is called.

componentDidLeave():

Called after the callback function, which was passed to the above componentWillLeave gets called.

What is CSSTransition?

We already have seen above that the CSSTransition component is an extension of the normal Transition component provided by the react-transition-group library. And as it is built on top of that, therefore it inherits all of its properties. And as it is preferred over the standard Transition component, let's try to look more into it.

Creating Transitions Using CSS Transition

  • CSS Transition Timeout Prop
  • Adding the Appear Prop to Display Transition on Load
  • Using Enter and Exit Props
  • More Lifecycle Props in CSSTransition Groups

Notes for the contents team:
Already soundly explained all of these concepts above using various examples, and there it's better into the flow, I can write it again here, but it will be redundant and will break the learning pattern as well.

Simple List Example with Transition Component

Let's now look at an example of a simple list showcasing animations from the react-transition-group library.

App.js file:

CSS File:

Output:

simple-list-example-with-transition-component

Explanation:

Here in the App.js file, we initially have a state variable named show, which is by default set to false. We also have a toggleShow() method to toggle the state of the show variable.

Inside the JSX, we have a button that calls the toggleShow() function to change the state of the show variable upon clicking. And then, we have the CSSTransition component, which is rendering an unordered list of hobbies.

In the output, we can see that when the button gets clicked, the change in the state slowly changes the color of the list items, representing the six states, as we discussed above, from which an element passes.

Transitions of Elements in a List Using Transition Group and CSSTransition

Let's see another example to understand the use of react-transition-group in a better way.

CSS File:

Output:

transitions-of-elements-in-a-list-using-transition-group-and-csstransition

Explanation:

Here, inside the App.js file, we initially have a state array variable named favItems which is by default set to empty. Then we have a toggleInFav() function, which takes an item as a parameter and tries to find the passed item if that exists in the favItems state array. If the returned result is true, i.e., the item exists in the favItems array, then we get into the if block, remove that item from there, and update the list. But if the item does not exist, then we add that item into the favItems array using the spread operator. As the name says, the Spread operator spreads the whole array here, adds the passed item, and then returns it as an updated array.

Inside the JSX, we are firstly listing out the items array, which we have initialized in our app; inside it, we are having a li item rendered which displays the name of the item, and a span element which calls the toggleInFav() function to add that specific item to the favItems array.

Then after we are rendering our TransitionalGroup component as a ul element, inside it, we have the CSSTransition component, which lists out the elements from the favItems array as our favorite items.

Transitions Using JSS

We have written our CSS files in the standard vanilla css approach. But we can also write those styles as a JSS, meaning in the JavaScript form as objects. So let's have a look at how we can do that.

App.js file:

Output:

transitions-using-jss

Conclusion

  • react-transition-group is a react library that provides us with ways to transition components in and out of the DOM more efficiently.
  • It lets us visualize the different lifecycle methods an element or component passes through. For example
    • componentWillAppear()
    • componentDidAppear()
    • componentWillEnter()
    • componentDidEnter()
    • componentWillLeave()
    • componentDidLeave()
  • react-transition-group primarily provides us with three different types of components - Transition, CSSTransition, and TransitionGroup.
  • The Transition component lets us describe transitions in a specific component from one state to another state.
  • The CSSTransition component is an extension to the standard Transition component, most commonly used to demonstrate the mounting and unmounting of a component.
  • The TransitionGroup component does not define any animation behavior of its own; instead, it behaves like a parent group that manages the transition states of its child components.