How to animate element height in React with ReactCSSTransitionGroup?

Cherry Ng picture Cherry Ng · Mar 30, 2015 · Viewed 25.1k times · Source

I'm trying to animate element height with ReactCSSTransitionGroup, so this is what I would want the animation looks like:

http://jsfiddle.net/cherrry/hgk4Lme9/

The problem is that I don't always know the element height, so I tried to hack the scrollHeight, clientHeight or something similar during componentDidMount and try to set node.style.height or add rules to stylesheet

http://jsfiddle.net/cherrry/dz8uod7u/

Leaving animation looks good, however when element enters, it flash a bit and the scaling animation looks strange

It should be because of asking node.scrollHeight caused the rendering occur immediately, so is there anyway to get the same information and inject css rules before animation start? Or should I think other way round?

I'm not very satisfied with the max-height solution, as the resulting animation speed will be very strange when max-height is not close to or smaller to height, and my components' height do vary a lot.

I could imagine the final solution could be a bit messy, but I think making it into a Mixin will be nice enough to reuse it anywhere

Answer

Stanko picture Stanko · Jun 30, 2017

I had a same problem and ended up writing a standalone component for animating height.

You can see the demo here: https://stanko.github.io/react-animate-height/

It is much easier to use, and whole library is really small (~200 lines)

<AnimateHeight
  duration={ 500 }
  height={ 'auto' }
>
  <h1>Your content goes here</h1>
  <p>Put as many React or HTML components here.</p>
</AnimateHeight>

Sorry for the shameless self promotion, but I think it can save you a lot of time if you have more than one component to animate.

Cheers!