useSynchronizedAnimation
A react hook to synchronize CSS animations across multiple elements.
Press Enter to start editing
<div>
<button class="ds-button" type="button" style="display:block">New box</button>
<div
style="display:flex;gap:10px;max-width:300px;flex-wrap:wrap"
>
<div
style="animation:spin 2s linear infinite;width:30px;height:30px;background-color:red"
></div>
</div>
<style>
@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform:
rotate(360deg); } }
</style>
</div>const Preview = () => { /* const SyncedBox = () => { const ref = useSynchronizedAnimation<HTMLDivElement>('spin'); return ( <div ref={ref} style={{ animation: 'spin 2s linear infinite', width: '30px', height: '30px', backgroundColor: 'red', }} /> ); }; */ const [count, setCount] = useState(1); return ( <div> <Button onClick={() => setCount(count + 1)} style={{ display: 'block' }}> New box </Button> <div style={{ display: 'flex', gap: '10px', maxWidth: '300px', flexWrap: 'wrap', }} > {Array.from({ length: count }).map((_, i) => ( /* @ts-ignore */ <SyncedBox key={i} /> ))} </div> <style> {` @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } `} </style> </div> ); }; render(<Preview />)
You pass in the name of the animation you want to synchronize.
The hook returns a ref, which you pass to your element.
The animation on your element will be synchronized to the first animation with the same name on the page.
Bruk
const SyncedBox = () => {
const ref = useSynchronizedAnimation<HTMLDivElement>('spin');
return <div ref={ref} />;
};