const { useEffect, useRef, useState } = React;
function Box({ children, timeline, index }) {
const el = useRef();
// add 'left 100px' animation to timeline
useEffect(() => {
timeline && timeline.to(el.current, { x: -100 }, index * 0.1);
}, [timeline]);
return <div className="box" ref={el}>{children}</div>;
}
function Circle({ children, timeline, index, rotation }) {
const el = useRef();
useEffect(() => {
// add 'right 100px, rotate 360deg' animation to timeline
timeline && timeline.to(el.current, { rotate: rotation, x: 100 }, index * 0.1);
}, [timeline, rotation]);
return <div className="circle" ref={el}>{children}</div>;
}
function App() {
const [reversed, setReversed] = useState(false);
const [tl, setTl] = useState();
useEffect(() => {
const tl = gsap.timeline();
setTl(tl);
}, []);
useEffect(() => {
tl && tl.reversed(reversed)
}, [reversed, tl]);
return (
<div className="app">
<button onClick={() => setReversed(!reversed)}>Toggle</button>
<Box timeline={tl} index={0}>Box</Box>
<Circle timeline={tl} rotation={360} index={1}>Circle</Circle>
</div>
);
}
ReactDOM.render(<App />, document.querySelector("#root"));
View Compiled