Hi, I want to use gsap to animate the two pseudo elements (::before and ::after) of my buttons. The each button element is inside a Group component in my react project. I want to play the animations on ::before and ::after alternately. Here is my code:
import React, { useState } from "react";
import { gsap } from "gsap";
import { CSSRulePlugin } from "gsap/CSSRulePlugin";
const animation = (qseudoElement) => {
gsap.registerPlugin(CSSRulePlugin);
const qseudo = CSSRulePlugin.getRule(qseudoElement);
const tl = gsap.timeline();
tl.fromTo(
qseudo,
{
cssRule: {
opacity: 0,
scale: 0
}
},
{
cssRule: {
opacity: 1,
scale: 1
},
duration: 1
}
);
tl.to(qseudo, {
cssRule: {
scale: 0,
opacity: 0
},
duration: 1
});
};
const Group = () => {
const [count, setCount] = useState(0);
const handleClick = () => {
setCount(count + 1);
if (count % 2 === 0) {
animation(".btn::before");
} else {
animation(".btn::after");
}
};
return (
<div>
<button className="btn" onClick={() => handleClick()}>Click Me</button>
</div>
);
};
export default Group;
And I have multiple Group components in my App.
import Group from "./components/Group";
import "./styles.css";
export default function App() {
return (
<div className="App">
<Group />
<Group />
<Group />
</div>
);
}
The problem is that if I click on any button, the animations are fire on all buttons. I know this is because of they have the same css class. How can I select the button that is clicked and animate its pseudo elements? I want to achieve something like this:
const handleClick = (e) => {
setCount(count + 1);
if(count % 2 === 0){
animation(e::before);
} else {
animation(e::after);
}
}
I appreciate your help and I made a demo here: codesandbox