Skip to content

Instantly share code, notes, and snippets.

@daviddamilola
Created June 5, 2022 21:16
Show Gist options
  • Save daviddamilola/b298d57b80c50160c2f58339bd22fe64 to your computer and use it in GitHub Desktop.
Save daviddamilola/b298d57b80c50160c2f58339bd22fe64 to your computer and use it in GitHub Desktop.
FlipAnimationHook
import { useLayoutEffect, useRef, MutableRefObject } from 'react';
const useFlipAnimation = (
elemRef: MutableRefObject<HTMLDivElement | null>,
layoutChangeFn: (x: boolean) => void,
whenToRun: boolean
) => {
const justMounted = useRef(true);
useLayoutEffect(() => {
if (justMounted.current) {
justMounted.current = false;
return;
}
if (!justMounted.current) {
const elem = elemRef.current;
if (elem) {
const first = elem.getBoundingClientRect();
layoutChangeFn(whenToRun);
const last = elem.getBoundingClientRect();
const deltaX = first.left - last.left;
const deltaY = first.top - last.top;
const deltaW = first.width / last.width;
const deltaH = first.height / last.height;
elem.animate(
[
{
transformOrigin: 'top left',
transform: `
translate(${deltaX}px, ${deltaY}px)
scale(${deltaW}, ${deltaH})
`,
},
{
transformOrigin: 'top left',
transform: 'none',
},
],
{
duration: 300,
easing: 'ease-in-out',
fill: 'both',
}
);
}
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment