In the last couple of React tutorials, you got familiar with basic React concepts like JSX, routing, and forms. In this tutorial, we'll take it to the next level and try to understand animations in React.
Getting Started
Create a directory called ReactAnimations
. Navigate to the directory and initiate the project using Node Package Manager or npm.
mkdir ReactAnimations cd ReactAnimations npm init
Install react
and react-dom
to the project.
npm install react react-dom --save
We'll be using webpack
module bundler for this project. Install webpack
and webpack development server.
npm install webpack webpack-dev-server --save-dev
Install the babel
package to convert JSX
syntax to JavaScript in our project.
npm install --save-dev babel-core babel-loader babel-preset-react babel-preset-es2015
Create a configuration file required by webpack-dev-server
where we'll define the entry file, output file, and the babel loader. Here is how webpack.config.js
looks:
module.exports = { entry: './app.js', module: { loaders: [ { exclude: /node_modules/, loader: 'babel-loader?presets[]=es2015&presets[]=react' } ] }, output: { filename: 'bundle.js' } };
Create an index.html
file where the application will be rendered. Here is how it looks:
<html> <head> <title>TutsPlus - React Animations</title> </head> <body> <div id="app"></div> <script src="bundle.js"></script> </body> </html>
Create a file called app.js
. Inside app.js
import the required react libraries as shown:
import React from 'react'; import {render} from 'react-dom';
Create a stateless component called Home
which renders a H1
tag.
const Home = () => { return ( <h2>{'TutsPlus - Welcome to React Animations!'}</h2> ); };
Render the Home component inside the app element in the index.html
page. Here is how app.js
looks:
import React from 'react'; import {render} from 'react-dom'; const Home = () => { return ( <h2>{'TutsPlus - Welcome to React Animations'}</h2> ); }; render( <Home />, document.getElementById('app') );
Save the above changes and start the webpack
server. You should have your app running at http://localhost:8080/index.html.
Animations in React
React provides a number of add-on utilities for creating React apps. TransitionGroup
and CSSTransitionGroup
are the APIs provided for animation.
From the official documentation,
TheReactTransitionGroup
add-on component is a low-level API for animation, andReactCSSTransitionGroup
is an add-on component for easily implementing basic CSS animations and transitions.
Appear Animation
Let's start by trying out a simple animation in React. Install the react-addons-css-transition-group
to the project.
npm install react-addons-css-transition-group --save
Import ReactCSSTransitionGroup
inside the app.js
file.
import ReactCSSTransitionGroup from 'react-addons-css-transition-group'
Inside the Home
component that you created, wrap up the h2
tag inside the ReactCSSTransitionGroup
tag.
<div> <ReactCSSTransitionGroup transitionName="anim" transitionAppear={true} transitionAppearTimeout={5000} transitionEnter={false} transitionLeave={false}> <h2>{'TutsPlus - Welcome to React Animations'}</h2> </ReactCSSTransitionGroup> </div>
Using the ReactCSSTransitionGroup
tag, you have defined the portion where animation would take place. You have specified a name for the transition using transitionName
. You have also defined whether the transition appear, enter and leave should happen or not.
Using the transition name defined inside the ReactCSSTransitionGroup
, you'll define the CSS classes which would be executed on appear and when in active state. Add the following CSS style to the index.html
page.
.anim-appear { opacity: 0.01; } .anim-appear.anim-appear-active{ opacity: 2; transition: opacity 5s ease-in; }
As you would have noticed, you need to specify the animation duration both in the render method and in the CSS. It's because that's how React knows when to remove the animation classes from the element and when to remove the element from the DOM.
Save the above changes and refresh the page. Once the page has loaded, within a few seconds you should be able to see the animated text.
Enter/Leave Animation
To get a better understanding of the enter and leave animation, we'll create a small React application. The app would have an input text box to enter the name. You'll see how to add the enter animation when a name is added to the list.
Inside app.js
, create a new class called App
.
class App extends React.Component { }
Initialize a data
list and a name
variable inside the initial state of the component.
class App extends React.Component { constructor(props) { super(props); this.state = { data: [], name:'' }; } }
Inside the render portion of the App component, place an input text box for entering the name and a button to add the name to the array list.
<div> Enter Name <input onChange={this.handleChange} type="text" /> <input onClick={this.add} type="button" value="Add" /> </div>
Define the input handleChange
event and the add
event inside the App component.
handleChange(e){ this.setState({name:e.target.value}) }
The handleChange
event sets the value of the input text box to the name
variable. Here is how the add method looks:
add(){ var arr = this.state.data.slice(); arr.push({'id':(new Date()).getTime(),'name':this.state.name}) this.setState({data:arr}) }
Inside the add
method, the entered name and a unique ID is pushed to the data
array list.
Bind the handleChange
and add
method in the App component's constructor.
constructor(props) { super(props); this.add = this.add.bind(this); this.handleChange = this.handleChange.bind(this); this.state = { data: [], name:'' }; }
You'll be displaying the entered names inside a list. Modify the render HTML code to add the list.
<ul> { this.state.data.map(function(player) { return <li key={player.id}>{player.name}</li> }) } </ul>
To animate the newly added items, we'll add the ReactCSSTransitionGroup
tag over the li
elements.
<ul> <ReactCSSTransitionGroup transitionName="anim" transitionAppear={false} transitionEnterTimeout={5000} transitionEnter={true} transitionLeave={false}> { this.state.data.map(function(player) { return <li key={player.id}>{player.name}</li> }) } </ReactCSSTransitionGroup> </ul>
Add the following CSS
transition style to the index.html
page.
.anim-enter { opacity: 0.01; } .anim-enter.anim-enter-active { opacity: 2; transition: opacity 5s ease-in; }
Here is the complete App component:
class App extends React.Component { constructor(props) { super(props); this.add = this.add.bind(this); this.handleChange = this.handleChange.bind(this); this.state = { data: [], name:'' }; } add(){ var arr = this.state.data.slice(); arr.push({'id':(new Date()).getTime(),'name':this.state.name}) this.setState({data:arr}) } handleChange(e){ this.setState({name:e.target.value}) } render() { return ( <div> Enter Name <input onChange={this.handleChange} type="text" /> <input onClick={this.add} type="button" value="Add" /> <ul> <ReactCSSTransitionGroup transitionName="anim" transitionAppear={false} transitionEnterTimeout={3000} transitionEnter={true} transitionLeave={false}> { this.state.data.map(function(player) { return <li key={player.id}>{player.name}</li> }) } </ReactCSSTransitionGroup> </ul> </div> ) } }
Save the above and refresh the page. Enter a name and enter the add button, and the item should be added to the list with animation.
Similarly, the leave animation can also be implemented in the above code. Once the delete functionality has been implemented in the application, add the leave
and leave-active
class to the index.html
. Set the transitionLeave
to True
in the ReactCSSTransitionGroup
tag in the render method, and you should be good to go.
Wrapping It Up
In this tutorial, you saw how to get started with using animations in React. You created a simple React app and saw how to implement the appear and enter animation. For in-depth information on animations in React, I would recommend reading the official documentation.
The source code from this tutorial is available on GitHub.
Over the last couple of year, React has grown in popularity. In fact, we’ve a number of items in the marketplace that are available for purchase, review, implementation, and so on. If you’re looking for additional resources around React, don’t hesitate to check them out.
Do let us know your thoughts in the comments below. Have a look at my Envato Tuts+ instructor page for more tutorials on React and related web technologies.
Comments