Skip to content

Instantly share code, notes, and snippets.

@paulborm
Last active October 25, 2020 16:56
Show Gist options
  • Save paulborm/e7d597bb5daa82244102606861070447 to your computer and use it in GitHub Desktop.
Save paulborm/e7d597bb5daa82244102606861070447 to your computer and use it in GitHub Desktop.
Custom React Hook for animating the height of a HTML Element.
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