Last active
October 25, 2020 16:56
-
-
Save paulborm/e7d597bb5daa82244102606861070447 to your computer and use it in GitHub Desktop.
Custom React Hook for animating the height of a HTML Element.
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 React from 'react'; | |
import gsap from 'gsap'; | |
function useAnimateHeight({ key, elementRef }) { | |
const prevKey = usePrevious(key); | |
const currentHeight = elementRef.current?.offsetHeight; | |
React.useEffect(() => { | |
if (!elementRef.current) { | |
return; | |
} | |
if (key !== prevKey) { | |
const newHeight = elementRef.current.scrollHeight; | |
if (currentHeight === newHeight) { | |
return; | |
} | |
gsap.fromTo( | |
elementRef.current, | |
{ height: currentHeight }, | |
{ | |
height: newHeight, | |
duration: 1, | |
ease: "power2.inOut", | |
clearProps: "height" | |
} | |
); | |
} | |
}, [elementRef, key, prevKey, currentHeight]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment