Using GSAP in ReactJS
I have encountered many animation libraries through which an animation can be added to react but i found GSAP to be most interesting and easy to use.In the below article i will make a short example of creating stagger effects in multiple lists.
first requirement is to install gsap on you machine.
npm install gsap --save
In this tutorial i will be using hooks but the implementation remains same for class based components with little tweakings and we’ll be using TimeLine for animation and for easing pace Power2 but there’s more you can go to their website and can chekout.
import React from ‘react’;
import {TimelineLite,Power2} from 'gsap'const Tutorial = () => {//creating a reference object for gsap
let timeline = new TimelineLite();//returns an array of length 10 with value "something"
let cards = Array(10).fill(“something”);return (<div>//1st Container with heading 1 and a list of 10 child cards
<div className=”container”>
<div className=”heading”>heading 1</div>
<div className=”content”>
{cards.map(card =>{return (<div className="card">{card}</div>)})}</div>
</div>//2nd Container with heading 2 and a list of 10 child cards
<div className=”container”>
<div className=”heading”>heading 2</div>
<div className=”content”>
{cards.map(card =>{return (<div className="card">{card}</div>)})}</div>
</div></div>);};export default Tutorial;
so Above is the basic structure that we will be using.
//css file.container{
text-align: center;
flex:1
text-transform: uppercase;
}.flex{
display:flex;
margin-top:5vh;
}.card{
background-color: aquamarine;
padding: 10px;
text-transform: uppercase;
margin: 2vh;
}
Now modify below snippet
//giving reference to all cards
let cardRef = useRef({heading1:[],heading2:[]});//for heading 1
{cards.map((card,index) =>{return (<div className="card" ref={el => {cardRef.current.heading1[index] = el}}>{card}</div>)})}//for heading 2
{cards.map((card,index) =>{return (<div className="card" ref={el => {cardRef.current.heading2[index] = el}}>{card}</div>)})}
Lastly you just have to add a animation and i am using useEffect hook for immediate execution of animation
useEffect(()=>{
timeline.staggerFrom(cardRef.current.heading1,0.3,{y:-10,opacity:0,ease:Power2.easeInOut},0.3)
.staggerFrom(cardRef.current.heading2,0.3,{y:-10,opacity:0,ease:Power2.easeInOut},0.3)},[])
Hope this tutorial helped you.