Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

You can activate a GSAP animation in React when a button is clicked by adding an event listener to the button which triggers the animation when clicked. Here's an example:

  1. Import GSAP:
import { gsap } from "gsap";
  1. Write a function that contains the GSAP animation code:
const animate = () => {
  gsap.from(".box", {
    duration: 1,
    x: -100,
    opacity: 0,
  });
};

This function will animate an element with the class name "box" by moving it 100px to the left and fading it in from 0 opacity to 1 over a duration of 1 second.

  1. Add an event listener to the button that triggers the animation:
const handleClick = () => {
  animate();
};

return (
  <button onClick={handleClick}>Animate</button>
);

This code creates a button element with the text "Animate" and adds an onClick event listener to it. When the button is clicked, the handleClick function is called, which in turn calls the animate function that contains the GSAP animation code.

  1. Add the element you want to animate to your React component:
return (
  <div>
    <button onClick={handleClick}>Animate</button>
    <div className="box">Hello World!</div>
  </div>
);

This code adds a div element with the class name "box" that contains the text "Hello World!". When the animation is triggered, this element will be animated according to the GSAP animation code in the animate function.

And that's it! Now when you click the "Animate" button, the GSAP animation will be triggered and the element with the class name "box" will be animated accordingly.