Introduction to Animations in React
source link: https://code.tutsplus.com/tutorials/introduction-to-animations-in-reactjs--cms-28083
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Introduction to Animations in React
When building applications, animations are a great way to improve the overall user experience because they allow for greater interaction between the app and the user.
In some of our previous 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. While there are many ways to add animations to a React application, we'll focus on the React Transition Group and how to use it in this article.
Animations in React
React provides a number of add-on utilities for animating React apps, one of which is called the React Transition Group, created by the React developers team.
It's not a library that sets animation styles; rather, it's a low-level API with four types of built-in components: Transition
, CSSTransition
, SwitchTransition
, and TransitionGroup
. As a result, animating React components in and out of the DOM during state changes is simple.
The React Transition Group is a very simple tool to get started with, and because it's lightweight, it speeds up the development process by reducing the need for boilerplate code.
Getting Started
First, let's install react
using the create-react-app
package in our terminal.
npx create-react-app react-animations |
Open the index.html file of the public folder and edit the title like so:
< title >TutsPlus - React Animations</ title > |
Let's create a folder named components in the src folder of our application and create a Home.js file. Next, we update this file by creating a functional component called Home
and rendering an h2
tag.
import React from "react" ; const Home = () => { return ( <> <h2>{ "TutsPlus - Welcome to React Animations!" }</h2> </> ); }; export default Home; |
Next, update the App.js file by importing the Home
component:
import React from "react" ; import Home from "./components/Home" ; const App = () => { return ( <> <Home /> </> ); }; export default App; |
Then, start the development server by running:
npm run start |
React Transition Group Setup
Let's start by trying out a simple animation in React by installing the react-transition-group
package to the project.
npm install react-transition-group |
Next, we import the four components mentioned earlier from the react-transition-group
package inside the Home.js file.
import {Transition, CSSTransition, SwitchTransition, TransitionGroup} from "react-transition-group" ; |
Next, we'll see how each one of these components works.
The Transition
Component
The Transition
component provides an API for defining transitions in a component from one state to another during mounting and unmounting.
Now, in the Home
component, wrap up the h2
tag inside the Transition
component and update the code like so.
import React, { useState } from "react"; const duration = 300; const defaultStyle = { transition: `opacity ${duration}ms ease-in-out`, opacity: 0, }; const transitionStyles = { entering: { opacity: 1 }, entered: { opacity: 1 }, exiting: { opacity: 0 }, exited: { opacity: 0 }, }; const Home = () => { const [inProp, setInProp] = useState(false); return ( <> < div > < Transition in={inProp} timeout={300}> {(state) => ( < h2 style={{ ...defaultStyle, ...transitionStyles[state], }} > {"TutsPlus - Welcome to React Animations"} </ h2 > )} </ Transition > < button onClick={() => setInProp(!inProp)}> Click to {inProp ? "Exit" : "Enter"} </ button > </ div > </> ); }; export default Home; |
Using the Transition
tag, we've defined the portion where animation would take place. We also specified an in
prop for the transition using inProp
state, which toggles the transition state.
As you would have noticed, we specified the animation duration both in the defaultStyle
above and in the Transition
component using a timeout
prop. 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.
The CSSTransition
Component
When trying to implement a CSS-based animation to your React component, the CSSTransition
component comes in handy.
Because this component is based on the Transition
component, it inherits all of that component's props and also makes use of a couple of classes to define transitions.
To see how this works, let's add the following code to the index.css file as shown below:
.react-animations-enter { opacity: 0 ; } .react-animations-enter-active { opacity: 1 ; transition: opacity 200 ms; } .react-animations-exit { opacity: 1 ; } .react-animations-exit-active { opacity: 0 ; transition: opacity 200 ms; } |
From *-enter
to *-exit-active
, each class defines transitions for when components are in the "entering", "entered ", "exiting", and "exited" states.
Then, in Home.js, we'll wrap up our component content into the CSSTransition
tag, passing in the in
and timeout
props as well as the classes we defined earlier:
<div> <CSSTransition in ={displayText} timeout={300} classNames= "react-animations" unmountOnExit > <h2>{ "TutsPlus - Welcome to CSSTransition" }</h2> </CSSTransition> <button onClick={() => setDisplayText(!displayText)}> Display Text </button> </div> |
Notice that the classNames
prop above has a react-animations
value, which applies to all the classes defined.
The SwitchTransition
Class
As the name "switch" suggests, this component is useful when you want to switch rendering between state transitions depending on a selected mode: in-out or out-in mode. It can be useful in scenarios where you want a component to fade out while you insert another.
To access the properties of this utility, we'll also wrap the contents of a component within the SwitchTransition
tag. It's also important to note that the SwitchTransition
should be used alongside the Transition
or CSSTransition
components.
Let's add the following code to the index.css
file as shown below to create our classes:
.fade-enter{ opacity: 0 ; } .fade-exit{ opacity: 1 ; } .fade-enter-active{ opacity: 1 ; } .fade-exit-active{ opacity: 0 ; } .fade-enter-active, .fade-exit-active{ transition: opacity 500 ms; } |
Let's see how it works, starting with the out-in mode, which is the default mode:
const [state, setState] = useState( false ); <SwitchTransition> <CSSTransition key={state ? "Did you Enjoy our Tutorial?" : "Welcome to TutsPlus" } addEndListener={(node, done) => node.addEventListener( "transitionend" , done, false )} classNames= 'fade' > <button onClick={() => setState(state => !state)}> {state ? "Did you Enjoy our Tutorial?" : "Welcome to TutsPlus" } </button> </CSSTransition> </SwitchTransition> |
The key
prop in the code above keeps track of the state in the component, while the addEndListener
prop prevents components from flipping almost instantly. Without it, it would appear as if no animation was implemented.
Next is the in-out mode, whereby the SwitchTransition
tag takes in a mode
prop with a in-out
value. Now update your code to see how it works:
<SwitchTransition mode={ "in-out" }> {Code goes here} </SwitchTransition> |
TransitionGroup
This component helps to manage Transition
or CSSTransition
components in a list. Below is an example of how it can be applied.
Update Home.js like so:
const [items, setItems] = useState([ "Manal" ]); const CONTACTS = [ "Jane" , "Fred" , "John" , "Doe" , "Brown" ]; const onAddContacts = () => { const newItem = CONTACTS.find((item) => !items.includes(item)); if (newItem) { setItems((prev) => [...prev, newItem]); } }; <div> <TransitionGroup> <h2>Contacts</h2> {items.map((item, index) => ( <CSSTransition key={index} timeout={900} classNames= "fade" > <p>{item}</p> </CSSTransition> ))} <button onClick={onAddContacts}>Add a Contact</button> </TransitionGroup> </div> |
Save the above and refresh the page. Click on the button, and the item should be added to the list with animation.
From the code above, we initialized a static set of data
called CONTACTS
. Then, an onAddContacts
function, which will handle adding a new contact, was defined and triggered on the button.
Each item in the list was wrapped in a CSSTransition
tag to animate the newly inserted items. Finally, this component was wrapped within the TransitionGroup
component to manage the transitions included within it.
Here is the complete Home.js component:
import React, { useState } from "react" ; import { Transition, CSSTransition, SwitchTransition, TransitionGroup } from "react-transition-group" ; const duration = 300; const defaultStyle = { transition: `opacity ${duration}ms ease- in -out`, opacity: 0, }; const transitionStyles = { entering: { opacity: 1 }, entered: { opacity: 1 }, exiting: { opacity: 0 }, exited: { opacity: 0 }, }; const Home = () => { const [inProp, setInProp] = useState( false ); const [displayText, setDisplayText] = useState( false ); const [state, setState] = useState( false ); const [items, setItems] = useState([ "Manal" ]); const CONTACTS = [ "Jane" , "Fred" , "John" , "Doe" , "Brown" ]; const onAddContacts = () => { const newItem = CONTACTS.find((item) => !items.includes(item)); if (newItem) { setItems((prev) => [...prev, newItem]); } }; return ( <> <div> <Transition in ={inProp} timeout={300}> {(state) => ( <h2 style={{ ...defaultStyle, ...transitionStyles[state], }} > { "TutsPlus - Welcome to React Animations" } </h2> )} </Transition> <button onClick={() => setInProp(!inProp)}> Click to {inProp ? "Exit" : "Enter" } </button> </div> <div> <CSSTransition in ={displayText} timeout={300} classNames= "react-animations" unmountOnExit > <h2>{ "TutsPlus - Welcome to CSSTransition" }</h2> </CSSTransition> <button onClick={() => setDisplayText(!displayText)}> Display Text </button> </div> <div> <SwitchTransition mode={ "in-out" }> <CSSTransition key={state ? "Did you Enjoy our Tutorial?" : "Welcome to TutsPlus" } addEndListener={(node, done) => node.addEventListener( "transitionend" , done, false ) } classNames= "fade" > <button onClick={() => setState((state) => !state)}> {state ? "Did you Enjoy our Tutorial?" : "Welcome to TutsPlus" } </button> </CSSTransition> </SwitchTransition> </div> <div> <TransitionGroup> <h2>Contacts</h2> {items.map((item, index) => ( <CSSTransition key={index} timeout={900} classNames= "fade" > <p>{item}</p> </CSSTransition> ))} <button onClick={onAddContacts}>Add a Contact</button> </TransitionGroup> </div> </> ); }; export default Home; |
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 four React Transition Group components. 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.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK