Created
June 5, 2022 21:16
-
-
Save daviddamilola/b298d57b80c50160c2f58339bd22fe64 to your computer and use it in GitHub Desktop.
FlipAnimationHook
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 { 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