joppot

コピペで絶対動く。説明を妥協しない

プログラミング

Tutorial How to use GSAP animation with React

投稿日:2018年11月19日 更新日:


Abstract

Hello everyone it’s me candle. In this time we will use GSAP in React.
The famous js library which can easily use animation is jQuery.
However, it seems that compatibility between jQuery and React is bad.
And there are no functions
Also, as far as I know, React has no animation function that is easy to use(Yeah, Transition is).

But, all times and places, it is rare case that animation is not necessary when you have created a web service. There are many candidates when using animation with React.

Of course, you can import only the necessary functions and use them in minimum usage. Let’s try it.

This article uses a tutorial format.

Condition

  1. You have a React knowledge

Preparation

Create a new project. execute the command in the terminal.

create-react-app react-animation
cd react-animation

We will edit thesrc/App.js like this.

import React, { Component } from 'react'
import './App.css'

class App extends Component {
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <div>hello</div>
        </header>
      </div>
    )
  }
}

export default App

Next you edit src/App.css.

.App {
  text-align: center;
}

.App-header {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: calc(10px + 2vmin);
}

Install GSAP

We need two libraries gsap and react-gsap-enhancer to use gsap in React.
Install it this command.

yarn add gsap react-gsap-enhancer

Run animation only once

You should change writing code either a component that runs animation only once or more than once. First we will make a component that runs animation only once when it is mounted.

Make a src/componets folder.

mkdir src/components

Create a OneTimeCard component file.

touch src/components/OneTimeCard.js

The code is this.

import React from 'react'
import GSAP from 'react-gsap-enhancer'
import { TimelineMax } from 'gsap'

class OneTimeCard extends React.Component {
  constructor(props) {
    super(props)
    this.myCard = null
  }

  componentDidMount() {
    new TimelineMax().from(this.myCard, 1, { y: 20, opacity: 0 })
  }

  render() {
    return (
      <div>
        <div style={styles.box} ref={div => (this.myCard = div)}>
          <div>Card</div>
        </div>
      </div>
    )
  }
}

const styles = {
  box: {
    width: '120px',
    height: '120px',
    zIndex: 1,
    cursor: 'pointer',
    border: '1px solid black',
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
  },
}

export default GSAP()(OneTimeCard)

The most important part is here in these codes.

componentDidMount() {
  new TimelineMax().from(this.myCard, 1, { y: 20, opacity: 0 })
}

Display it with transparency 0 to 1 and moving 20px on the y axis in 1 second.

Open the src/App.js and edit like this.

import React, { Component } from 'react'
import OneTimeCard from './components/OneTimeCard'
import './App.css'

class App extends Component {
  constructor(props) {
    super(props)
  }

  render() {
    return (
      <div className="App">
        <header className="App-header">
          <OneTimeCard />
        </header>
      </div>
    )
  }
}

export default App

When launch the server and check it, You will see the card drifting from below.

yarn run start

Run an animation more than two times

Well, let’s try to create a more elaborate animation component this time.

Let’s create a component where the card appears with the animation when the button is pushed and the card disappears when the button is pushed again

Create a new SwitchingCard.js file.

touch src/components/SwitchingCard.js

The content like this.

import React from 'react'
import GSAP from 'react-gsap-enhancer'
import { TimelineMax } from 'gsap'

class SwitchingCard extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      isBox: false,
    }
    this.myElement = null
    this.myTween = new TimelineMax()
  }

  toggleBox() {
    if (!this.state.isBox) {
      this.addAnimation(this.createAnim.bind(this))
    } else {
      this.addAnimation(this.createExitAnim.bind(this))
    }

    this.setState(prevState => ({
      isBox: !prevState.isBox,
    }))
  }

  createAnim() {
    return this.myTween
      .to(this.myElement, 0.1, { display: 'flex', clearProps: 'transform' })
      .to(this.myElement, 1, { y: 10, opacity: 1 })
  }

  createExitAnim() {
    return this.myTween
    .to(this.myElement, 1, { y: -1, opacity: 0 })
    .to(this.myElement, 0, { display: 'none' })
  }

  render() {
    const { isBox } = this.state
    return (
      <div style={styles.wrapper}>
        <div onClick={this.toggleBox.bind(this)} style={styles.button}>
          Show
        </div>

        <div style={styles.box} ref={div => (this.myElement = div)}>
          <div>Card</div>
        </div>
      </div>
    )
  }
}

const styles = {
  wrapper: {
    position: 'relative',
  },
  button: {
    width: '110px',
    cursor: 'pointer',
    border: '1px solid black',
    padding: '5px 5px',
  },
  box: {
    position: 'absolute',
    bottom: '55px',
    width: '120px',
    height: '120px',
    zIndex: 1,
    cursor: 'pointer',
    border: '1px solid black',
    display: 'none',
    justifyContent: 'center',
    alignItems: 'center',
    opacity: 0,
  },
}

export default GSAP()(SwitchingCard)

Open the src/App.js, change the component to use.

import './App.css'
import React, { Component } from 'react'
import SwitchingCard from './components/SwitchingCard'

class App extends Component {
  constructor(props) {
    super(props)
  }

  render() {
    return (
      <div className="App">
        <header className="App-header">
          <SwitchingCard />
        </header>
      </div>
    )
  }
}

export default App

Before code explanation run it.
How is it ? You can confirm that you push the button then a card appears and push it again then it disappears.

I will explain what it is.

Manage animated target DOM with ref

Specify animation targets with React’s refs. Initializing the variable this.myElement = null which assigns the target DOM in the constructor ().

Define the target of refs in JSX.

<div style={styles.box} ref={div => (this.myElement = div)}>
  <div>Card</div>
</div>

By the way, React.createRef() introduced in React 16.x could not be used.

Recycle a instance of animation

Instead of creating instances of TimelineMax () each time you write an animation over and over, we create and reuse the this.myTween = new TimelineMax () instance in constructor ().

It has been used in the createAnim() function and the createExitAnim() function.

 createAnim() {
    return this.myTween
      .to(this.myElement, 0.1, { display: 'flex', clearProps: 'transform' })
      .to(this.myElement, 1, { y: 10, opacity: 1 })
  }

  createExitAnim() {
    return this.myTween.to(this.myElement, 1, { y: -1, opacity: 0 }).to(this.myElement, 0, { display: 'none' })
  }

Add continuous animation to GSAP

If animation continues more than once, you need to use this.addAnimation () of react-gsap-enhancer.

This is because the animation needs to take over the movements of the previous animation instead of moving independently of each other.

Your created animation was added to GSAP at the part.

   if (!this.state.isBox) {
      this.addAnimation(this.createAnim.bind(this))
    } else {
      this.addAnimation(this.createExitAnim.bind(this))
    }

If you change this part as shown below and execute it directly, the animation of the createAnim () and the animation of createExitAnim () are executed separately.

 if (!this.state.isBox) {
   this.createAnim()
 } else {
   this.createExitAnim()
 }

You must add the function of continuous animation to addAnimation.

Conclusion

We tried animation using GSAP with React. GSAP is the animation library with a very large volume, so please check yourself and try implementing.

It is a good idea to read the GSAP official Getting started and react parts once.

Getting Started with GSAP

https://greensock.com/get-started-js

Getting Started: React and GSAP Animations

https://greensock.com/react

スポンサードリンク

If you think this article is good, share it please

-プログラミング
-, ,

執筆者:


comment

Your email address will not be published. Required fields are marked *

関連記事

How to change the language form “en-US” to “en” by wordpres bogo

English 日本語 Abstract Hello everyone, It’s me candle. In this time, I will show you to customize bogo plugins. The bogo is wonderful plugin which can adapt the wordpress site to many languages as a simple. but, there is a problem that you can’t choose general English. When writing English articles, you may not always have to write it limited to country. However, you can choose ‘en-UK’, ‘en-CA’ and ‘en-US’, but ‘en’ can not be chosen in bogo. I checked the source code. The bogo got a language list from wordpress function, and there is no general English in it. …

React Project development environment building command create-react-app is too convenient

English 日本語 Abstract Hello everyone It’s me candle. In this time we will build a “react” development environment with create-react-app command and try to hello world. Past react development was created by installing babel and other packages from npm on your own using gulp or webpack. Past react development installed babel and other packages from npm and built servers with gulp and webpack. If you use the create-react-app command, you can create react environment easily. Let’s do it. Precondition Node is already installed

Using sphinx how to generate documents of python classes and functions

Abstruct Hello everyone it’s me candle. In this article I will explain how to make documents about classes and functions with Sphinx automatically. condition I will explain it using Python 3, but I think that it will probably work with python 2 as well. Prepare test files Create a main.py and dog.py. touch main.py dog.py Write this to the main.py from dog import Dog def main(): dog = Dog() dog.show_name() if __name__ == "__main__": main() Open the dog.py and write it. class Dog(object): def __init__(self, name="bob"): self.name = name def bark(): print("Bow Wow") def show_name(self): print(self.name) def get_name(self): return self.name …

Create plantUML with emacs using plantuml-mode

Autumn leaves on wood table Abstract Hello everyone it’s me candle. In this time, we will introduce plantuml-mode of emacs supporting plantUML. plantuml-mode has three functions. Syntax highlight Autocomplete Display UML preview There are plenty of settings, so let’s do it patiently. Precondition You had plantuml command I installed plantuml with brew. but it is ok you prepare jar file. If you don’t have it yet, please refer to here. Build PlantUML environment on Mac using brew Install plantuml-mode The latest version of plant-mode is not yet registered in el-get packages, so we will get it from github directly. For …

Use react-simple-format in React web

Abstract Hello everyone it’s me candle. In this article we will use simple-format in react. Simple format is famous for Ruby on Rails and is commonly used. React has a legacy react-simple-format and 16g’s made. The legacy lib is not useful, so I choose 16g’s made. https://github.com/16g/react-simple-format Condition Nothing Create project If you already have a React project please use it. If not, use the following command to create it. create-react-app simple_format_sample cd simple_format_sample How to use react-simple-format First install it. yarn add @16g/react-simple-format Open a appropriate component file. I write it in src/App.js. import React, { Component } from …


I work in the venture company as a CTO. I start to write program in University, first I learned java, C++ and PHP. In the company, I'm developing web services by Rails. I do like to automation.