In this tutorial, you will learn how to animate in React using the React CSS Transitions group. React-transition-group is a lower-level type of animation library, it makes it easier to do any sort of animation on any React component.
This is a React plugin for creating basic CSS transitions and animations. Install via the command line:
PS C:\Users\HP\react\react-project> npm install react-addons-css-transition-group
Create a stylesheets file in the src folder and link it to the index.html file via the <head> tag:
<link rel = "stylesheets" type="text/css" href="./style.css">
We are all set.
When a component performs a transition it goes through 4 stages:
These transition stages are toggled via an attribute ‘in
’.When it's true, the transition begins and the component enters the entering stage of the cycle. Now let’s create a fad-in and fade-out animation for a component.
Fade.js
In the example below, once the in prop evaluates to true, the animation starts. All the code should be more like a boilerplate, you don’t need to memorize them as long as you know what does what:
import React from 'react'
import { Transition } from 'react-transition-group'
const duration = 300
const defaultStyles = {
transition: `opacity ${duration}ms ease-in`,
opacity: 0
}
const transitionStyles = {
entering: {opacity: 0.5},
entered: {opacity: 1},
exiting: {opacity: 0.5},
exited: {opacity: 1},
}
const Fade = ({in: inProp}) => (
<Transition in= {inProp} timeout={duration}>
{state => (
<div style={{...defaultStyles, ...transitionStyles[state]}}>My Animation</div>
)}
</Transition>
)
export default Fade
The styling for each transition stage is defined and then passed into the HOC <Transition>
,