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.
Last active
May 25, 2022 20:28
-
-
Save twfahey1/6550fb1796c145452638d19bbef78087 to your computer and use it in GitHub Desktop.
React + GSAP component example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | |
</> | |
); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<AnimatedBackgroundHeading background_color="bg-green-400"/> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment