greensock / GSAP

GSAP (GreenSock Animation Platform), a JavaScript animation library for the modern web
https://gsap.com
19.56k stars 1.72k forks source link

React: How to properly animate state properties? #248

Closed mraak closed 6 years ago

mraak commented 6 years ago

With this code, the render is not happening because I assume setState is not called.

 componentDidUpdate(){
    const {targetX, targetY} = computeCoordinates()
    TweenLite.to(this.state, .3, {x: targetX, y: targetY})
 }

render(){
    const {x, y} = this.state
    return(
      <svg x={x} y={y}>
           <rect width={20} height={20} fill="blue"  />
      </svg>
    )
  }

How do I get state to update during animation so that the coordinates can get assigned?

I did find a workaround which was somewhat strange. I created a loop on requestAnimationFrame and simply reassigned the x y from state back to state with setState. Odd, or correct?

 loop(){
    const x = this.state.x
    const y = this.state.y
    this.setState({x, y})
    window.requestAnimationFrame(this.loop)
  }

  componentDidMount(){
    window.requestAnimationFrame(this.loop)
  }
  componentWillUnmount(){
    window.cancelAnimationFrame(this.loop)
  }
jackdoyle commented 6 years ago

I'm not much of a React guy myself, but does this thread answer your question?: https://greensock.com/forums/topic/14639-greensock-reactjs-components-needed/?tab=comments#comment-62563

This was also a valuable resource in general for using React and GSAP: https://greensock.com/forums/topic/12093-react-and-gsap/?tab=comments#comment-66752

mraak commented 6 years ago

Thanks for the links, they were really helpful. I ended up NOT animating the state properties as I was still encountering problems. But I did find a way to do what I want and created I very minimal and useful example here on codepen:

https://codepen.io/mraak/pen/Vyxqgb