Skip to content

Instantly share code, notes, and snippets.

@twfahey1
Last active May 25, 2022 20:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save twfahey1/6550fb1796c145452638d19bbef78087 to your computer and use it in GitHub Desktop.
Save twfahey1/6550fb1796c145452638d19bbef78087 to your computer and use it in GitHub Desktop.
React + GSAP component example

This is scaffolding for a React component that can properly use GSAP. We setup a random class selector to pass to GSAP when the component is ready. This assumes also some TailwindCSS classes to provide the styling.

import React, { useEffect, useState } from "react";
import { gsap } from "gsap";
import random from "random";
export function AnimatedBackgroundHeading(props) {
const defaultcomponentStateConfig = {};
const [componentState, setComponentState] = useState(
defaultcomponentStateConfig
);
componentState.updateValue = (key_to_update, value_to_update) => {
setComponentState((prevState) => ({
...prevState,
[key_to_update]: value_to_update,
}));
};
useEffect(() => {
// Setup a random class for this component, for GSAP to identify it.
const uuid = "box-" + random.int(0, 100000000);
console.log("Setting class up as " + uuid);
componentState.updateValue("class", uuid);
}, []);
useEffect(() => {
// Once we have a class, we can setup the GSAP animation.
if (typeof componentState.class !== "undefined") {
gsap.from("." + componentState.class, { duration: 3, scale: 4 });
}
}, componentState.class);
return (
<>
<div
className={
componentState.class + " w-5 h-5 " + props.background_color ??
"bg-green"
}
></div>
</>
);
}
<AnimatedBackgroundHeading background_color="bg-green-400"/>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment