We now have a youtube channel. Subscribe!

ReactJS | Animation

ReactJS | Animation


Hello folks! welcome back to a new section of our tutorial on ReactJS. In this section of our tutorial on ReactJS, we will be studying about ReactJS Animation.

Animation is an exciting feature of modern web application. It gives a refreshing feel to the application. React community provides many fine react based animation library like React Motion, React Reveal, Framer Motion, React Move, React Spring, react-animations, etc., React itself gives an animation library, React Transition Group as an add-on option earlier. It's an independent library enhancing the earlier version of the library. Let us learn React Transition Group animation library in this tutorial.

React Transition Group

ReactJS Transition Group library is a simple execution of animations. It does not do any animation out of the box. Rather, it exposes the core animation related informations. All animation is basically transition of element from one state to another. The library reveal minimum possible state of all element and they are given below -

  • Entering
  • Entered
  • Existing
  • Existed

The library gives option to set CSS style for each state and animates the element based on the styles when the element moves from one state to another. The library provides in prop to set the current state of the element. If in props value is true, it simply means the element is moving from the entering state to existing state. If in props value is false, then it mean the element is moving from existing to existed.


Transition

Transition is the basic component provided by the React Transition Group to animate an element. Let us create a simple application and try to fade in / fade out an element via Transition element.

First, create a new react application, react-animation-app making use of Create React App or Rollup bundler by following steps in Creating a React application tutorial.

Next, install React Transition Group library.

cd /go/to/project 
npm install react-transition-group --save

Next, open the application in your favorite editor.

Next, create an src folder beneath the root directory of the application.

Next, create a components folder under src folder.

Next, create a file, HelloWorld.js beneath the src/components folder and start editing.

Next, import React and animation library.

import React from 'react'; 
import { Transition } from 'react-transition-group'

Next, create a HelloWorld component.

class HelloWorld extends React.Component {
   constructor(props) {
      super(props);
   }
}

Next, define the transition related styles as JavaScript objects in the constructor.

this.duration = 2000;
this.defaultStyle = {
   transition: `opacity ${this.duration}ms ease-in-out`,
   opacity: 0,
}
this.transitionStyles = {
   entering: { opacity: 1 },
   entered: { opacity: 1 },
   exiting: { opacity: 0 },
   exited: { opacity: 0 },
};

Here,

  • defaultStyles sets the transition animation.
  • transitionStyles sets the styles for various states.

Next, set the initial state for the element in the constructor.

this.state = { 
   inProp: true 
}

Next, simulate the animation by changing the inProp values every three seconds.

setInterval(() => {
   this.setState((state, props) => {
      let newState = {
         inProp: !state.inProp
      };
      return newState;
   })
}, 3000);

Next, create a render function.

render() { 
   return ( 
   ); 
}

Next, add Transition component. Make use of this.state.inProp for inProp & this.duration for timeout prop. The Transition component expects a function, which returns the user's interface. It is basically a Render props.

render() {
   return (
      <Transition in={this.state.inProp} timeout={this.duration}>
         {state => ({
            ... component's user interface.
         })
      </Transition>
   );
}

Next, write the component's user interface inside a container and set the defaultStyles and transitionStyles for the container.

render() {
   return (
      <Transition in={this.state.inProp} timeout={this.duration}>
         {state => (
            <div style={{
               ...this.defaultStyle,
               ...this.transitionStyles[state]
            }}>
               <h1>Hello World!</h1>
            </div>
         )}
      </Transition>
   );
}

Finally, export the component.

export default HelloWorld

The complete code of the component is as follows -

import React from "react";
import { Transition } from 'react-transition-group';

class HelloWorld extends React.Component {
   constructor(props) {
      super(props);
      this.duration = 2000;
      this.defaultStyle = {
         transition: `opacity ${this.duration}ms ease-in-out`,
         opacity: 0,
      }
      this.transitionStyles = {
         entering: { opacity: 1 },
         entered: { opacity: 1 },
         exiting: { opacity: 0 },
         exited: { opacity: 0 },
      };
      this.state = {
         inProp: true
      }
      setInterval(() => {
         this.setState((state, props) => {
            let newState = {
               inProp: !state.inProp
            };
            return newState;
         })
      }, 3000);
   }
   render() {
      return (
         <Transition in={this.state.inProp} timeout={this.duration}>
            {state => (
               <div style={{
                  ...this.defaultStyle,
                  ...this.transitionStyles[state]
               }}>
                  <h1>Hello World!</h1>
               </div>
            )}
         </Transition>
      );
   }
}
export default HelloWorld;


Next, create a file, index.js under src folder and use HelloWorld component.

import React from 'react';
import ReactDOM from 'react-dom';
import HelloWorld from './components/HelloWorld';

ReactDOM.render(
   <React.StrictMode   
      <HelloWorld /   
   </React.StrictMode   ,
   document.getElementById('root')
);

Finally, create a public folder under the root folder and create index.html file.

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="utf-8">
      <title>React Containment App</title>
   </head>
   <body>
      <div id="root"></div>
      <script type="text/JavaScript" src="./index.js"></script>
   </body>
</html>

Next, serve the application making use of npm command.

npm start

Next, open the web browser and then enter http://localhost:3000 in the address bar and press enter.


CSSTransition

CSSTransition is built on top of Transition component and it improves the Transition component by introducing className prop. classNames prop refers the css class name used for various state of the element.

For example, classNames=hello prop refers the below css classes.

.hello-enter {
   opacity: 0;
}
.hello-enter-active {
   opacity: 1;
   transition: opacity 200ms;
}
.hello-exit {
   opacity: 1;
}
.hello-exit-active {
   opacity: 0;
   transition: opacity 200ms;
}

Next, we will be creating a new component HelloWordCSSTransition via CSSTransition component.

Open our react-animation-app application in your favorite editor.

Create new file HelloWorldCSSTransition.css under src/components folder and enter the transition classes.

.hello-enter {
   opacity: 1;
   transition: opacity 2000ms ease-in-out;
}
.hello-enter-active {
   opacity: 1;
   transition: opacity 2000ms ease-in-out;
}
.hello-exit {
   opacity: 0;
   transition: opacity 2000ms ease-in-out;
}
.hello-exit-active {
   opacity: 0;
   transition: opacity 2000ms ease-in-out;
}

Create a new file HelloWorldCSSTransition.js under src/components folder and then start editing.

Import React library and animation library.

import React from 'react'; 
import { CSSTransition } from 'react-transition-group'

Next, import HelloWorldCSSTransition.css.

import './HelloWorldCSSTransition.css'

Next, create the HelloWorld component.

class HelloWorldCSSTransition extends React.Component {
   constructor(props) {
      super(props);
   }
}

Next, define the duration of the transition in the constructor.

this.duration = 2000;

Next, set the initial state for the element in the constructor.

this.state = { 
   inProp: true 
}

Next, simulate the animation by changing the InProp values every three seconds.

setInterval(() => {
   this.setState((state, props) => {
      let newState = {
         inProp: !state.inProp
      };
      return newState;
   })
}, 3000);

Next, create a render method.

render() { 
   return (
   ); 
}

Next, add a CSSTransition component. Use this.state.inProp for inprop, this.duration for timeout prop and hello for className prop. The CSSTransition component expects user interface as child prop.

render() {
   return (
      <CSSTransition in={this.state.inProp} timeout={this.duration} 
         classNames="hello">
         // ... user interface code ...   
      </CSSTransition>
   );
}

Next, write the component's user interface.

render() {
   return (
       <CSSTransition in={this.state.inProp} timeout={this.duration} 
      classNames="hello">
      <div>
          <h1>Hello World!</h1>
      </div>
       </CSSTransition>
   );
}

Finally, export the component.

export default HelloWorldCSSTransition;

The complete code of the component is as follows -

import React from 'react';
import { CSSTransition } from 'react-transition-group'
import './HelloWorldCSSTransition.css' 

class HelloWorldCSSTransition extends React.Component {
   constructor(props) {
      super(props);
      this.duration = 2000;
      this.state = {
         inProp: true
      }
      setInterval(() => {
         this.setState((state, props) => {
            let newState = {
               inProp: !state.inProp
            };
            return newState;
         })
      }, 3000);
   }
   render() {
      return (
         <CSSTransition in={this.state.inProp} timeout={this.duration} 
            classNames="hello">
            <div>
               <h1>Hello World!</h1>
            </div>
         </CSSTransition>
      );
   }
}
export default HelloWorldCSSTransition;


Next, create a file, index.js under src folder and use HelloWorld component.

import React from 'react';
import ReactDOM from 'react-dom';
import HelloWorldCSSTransition from './components/HelloWorldCSSTransition';

ReactDOM.render(
   <React.StrictMode>
      <HelloWorldCSSTransition />
   </React.StrictMode>,
   document.getElementById('root')
);

Next, serve the application making use of npm command.

npm start

Next, open the web browser and then enter http://localhost:3000 in the address bar and press enter.

The message will fade in and out for every three seconds.


TransitionGroup

TransitionGroup is a container component, which manages many transition component in a list. For example, while each item in a list uses CSSTransition, TransitionGroup can be used for grouping all the item for proper animation.

<TransitionGroup>
   {items.map(({ id, text }) => (
      <CSSTransition key={id} timeout={500} classNames="item" >
         <Button
            onClick={() =>
               setItems(items =>
                  items.filter(item => item.id !== id)
               )
            }
            >
            &times;
         </Button>
         {text}
      </CSSTransition>
   ))}
</TransitionGroup>


Alright guys! This is where we are going to be rounding up for this tutorial. In our next tutorial, we are going to be studying about ReactJS Testing.

Feel free to ask your questions where necessary and we will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.

Post a Comment

Hello dear readers! Please kindly try your best to make sure your comments comply with our comment policy guidelines. You can visit our comment policy page to view these guidelines which are clearly stated. Thank you.
© 2022 ‧ WebDesignTutorialz. All rights reserved. Developed by Jago Desain