Stanko / react-animate-height

Lightweight React component for animating height using CSS transitions. Slide up/down the element, and animate it to any specific height.
https://muffinman.io/react-animate-height
MIT License
758 stars 53 forks source link

Trigger immediate animation on render #144

Closed guitarhero17 closed 1 year ago

guitarhero17 commented 1 year ago

Hey @Stanko, thank you for this library!

I was wondering if it's possible to start the animation to the desired height immediately after the component is rendered. This will be helpful with conditional rendering / lazy-loading. For example:

{someCondition && (
  // Immediately animating height from 0 to auto
  <AnimateHeight height={'auto'}>....</AnimateHeight>
)}

Not sure if that's already possible or it'd require implementing a new feature.

Thanks and have a good one!

Stanko commented 1 year ago

Hey, You can use useEffect to detect when components is mounted and change the height, like this:

const AnimateOnInit = ({ children }) => {
  const [height, setHeight] = useState(0);

  useEffect(() => {
    setHeight("auto");
  }, []);

  return (
    <AnimateHeight height={height}>
      {children}
    </AnimateHeight>
  );
};

Check the demo here: https://codesandbox.io/s/react-animate-height-v3-basic-example-forked-jdy464?file=/src/index.js

Cheers!

guitarhero17 commented 1 year ago

Thanks @Stanko for the quick reply. Don't know why I did not came up with using useEffect for detecting the mount myself 😆

Stanko commented 1 year ago

It happens :) glad I could help!