sriram hegde
sriram hegde

Reputation: 2471

Animating element on enter/exit in react gsap

Basically I want to animate with gsap in react on enter/exit of an element , there seems to be no way to do this without complex hacks, I'm new to react animations and GSAP, can anyone please help atleast guide me where to look, Basically I have a input element and a button , when the button is clicked the input should smoothly vanish and then get unmounted based on button state, I need help in enter/exit of elements. This is my code:

class LoginBox extends React.Component {

     constructor(props) {
            super(props);
            this.myElement = null;

     }



     componentWillLeave(callback) {
         gsap.to(this.myElement, 6, {opacity: 0, onComplete: callback});
    }

    render(){
      return(
    <form>
                     {
                         this.props.loginButton.isSelected && <input ref={input => this.myElement = input}   type="text" placeholder="Enter email address"/>

                     }

)
}

Upvotes: 0

Views: 1464

Answers (1)

NickG
NickG

Reputation: 601

You could use a Higher-Order-Component or a Wrapper Component that handles the mounting of your Component.

As you might have guessed, animating a component after mounting is not the issue, as you can access it usually in componentDidMount, but the problem is how to animate it when it is unmounting, as the html is no longer rendered afterwards.

You can try to delay the unmounting for the unmounting animation to finish. There is a good article with an example of how to do it here (credit to Tomasz Ferens for posting it!).

If you wrap your animated components with this Higher Order Component, you can then check your new props in your animated components life-cicle hooks 'componentWillMount' and 'componentDidUpdate' to trigger the animations of your component:

  class YourAnimatedComponent extends Component {
    container = React.createRef();

    componentDidMount() {
      //component is mounting initally
      this.mount();
    }

    componentDidUpdate(prevProps, prevState) {
      //component is unmounting
      if (prevProps.isMounted && !this.props.isMounted) {
        this.unmount();
      }
      //component is mounting
      else if (!prevProps.isMounted && this.props.isMounted) {
        this.mount();
      }
    }

    mount = () => {
      //logic for animation in, e.g.:
      //TweenMax.to(this.container.current, .3, {css: {opacity: 1}});
    }

    unmount = () => {
      //logic for animation out e.g.:
      //TweenMax.to(this.container.current, .3, {css: {opacity: 0}});
    }
    ...
    render() {
      return(<div ref={this.container}>your content</div>);
    }
  }

I hope this gives you the nudge in the right direction.

Upvotes: 1

Related Questions