Jump to content
GreenSock

Search In
  • More options...
Find results that contain...
Find results in...
env828

Simple Example of GSAP with React

Recommended Posts

I am pretty new to GSAP and like using it so far, however, I have a question on how to do some relatively simple animations with react.js involved.

 

I have two divs and an arrow in the middle. What I want is when a div is clicked the arrow will animate and move under the div that is clicked. And if the other div is clicked then the arrow will move under that div. 

 

I feel like this is easily done with HTML/CSS but incorporating it into react has been difficult.

 

Any help is greatly appreciated coming from a entry-level coder.

 

Link to comment
Share on other sites

Hi and welcome to the GreenSock forums.

 

When starting up, using GSAP in a React app consist mostly in getting the DOM elements available for GSAP. The approach that React gives is using the ref callback to keep an instance of the DOM element available:

 

https://reactjs.org/docs/refs-and-the-dom.html

 

Here's a very simple example of that way to access an arrow and move it depending on the click target:

 

See the Pen qyyEOJ?editors=0010 by rhernando (@rhernando) on CodePen

 

The key is in this code:

<img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/33073/arrow.png" className="arrow"
  ref={ e => this.arrow = e }
/>

 

The ref to the DOM element is stored in the component's constructor so it can be accessed to any method binded to the class instance, that's why we can use it in the click event handler of each box.

 

Happy tweening!!!

  • Like 3
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×