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
756 stars 53 forks source link

Animate height when content changes #122

Closed thiemeljiri closed 2 years ago

thiemeljiri commented 2 years ago

Hi,

I'm struggling with the following. How to achieve animation of the height when content (height) changes? To be used e.g. with tabs.

I tried the following, but it doesn't work as expected. I also tried setting the height explicitly, getting it via ref of the content, that also didn't work well.

<AnimateHeight
  duration={300}
  height={'auto'}
>
  <div className="content" key={currentIndex}>{currentContent}</div>
</AnimateHeight>

Thank you!

BR, Jiri

Stanko commented 2 years ago

Hey @thiemeljiri, Unfortunately AnimateHeight wasn't made with swapping children in mind. It adds a certain level of complexity and I want to keep the component lighter.

However, this wasn't the first time I was asked this, so I created a codepen to show how it can be done: https://codepen.io/stanko/pen/eGwNZd?editors=0010

Hope that helps, cheers!

thiemeljiri commented 2 years ago

Hi @Stanko, I'm a bit surprised you came up with a solution which is not using this component. Actually I was able to make it work in combination with @rehooks/component-size. I used that to calculate the height of an inner wrapped and feeding the calculated height to your AnimateHeight wrapper. Let's try that and if you find that useful, maybe suggest a solution like this in the documentation (not necessarily that hook in particular, just "a hook calculating and updating the height").

BR, Jiri

Stanko commented 2 years ago

Well, it is not a trivial task, as components needs to take care of it's previous children, save a copy, swap them in place... And I just feel it doesn't belong in AnimateHeight.

It is worth mentioning in the documentation though. If you can share your implementation I would like to see it, and do a short paragraph in docs based on it.

inker commented 1 year ago

@thiemeljiri Try this:

import AnimateHeight from "react-animate-height";

// ...

const [height, setHeight] = useState(0);

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

const setHeightToNumeric = (newHeight) => {
  if (height === "auto") {
    setHeight(newHeight);
  }
};

// ...

<AnimateHeight
  duration={300}
  height={height}
  onHeightAnimationEnd={setHeightToNumeric}
>
  {/* children */}
</AnimateHeight>;

Where resetKey can be any value triggering the re-render.