Brent Brent - 5 months ago 49
React JSX Question

React.js set CSS attribute (similar to setState)

In React.js, how do you set CSS explicitly?

Here's the context:

I have a bar that starts at full height, then shrinks (via animation) in height all the way to 0px. See the image below.

enter image description here
It works correctly in step 1-2-3. I apply an animation to set the height to 0.

However, I am unable to transition from step 3 to step 4, because the height is already 0. (Unlike in step 1, where the height is at its initial value of 700px).

How can I explicitly set the CSS? This will let me restore the initial 700px height, which will allow the animation to be reset properly.

Note: I am not using jQuery for performance reasons.


You could explicitly set the CSS property of a div using the componentDidUpdate and componentDidMount methods and a ref to your div, like so:

endAnimation () {
     this.refs.animatedDiv.className = "newClassToReset"
  }, this.animationLength);
componentDidMout (){ 
componentDidUpdate (){

however if you are doing animations using CSS it is much better to use the official ReactCSSTransitionGroups plugin, found here:

It is really easy to set it up, it would be something like this for your example:

<ReactCSSTransitionGroup transitionName="shrink" transitionAppear={true} transitionAppearTimeout={500}>
  <div className="bar">Bar</div>

Then in your CSS file you supply the following classes:

.shrink-appear {
  height: 700px;

.shrink-appear.shrink-appear-active {
  height: 0;
  transition: height 500ms ease-in;

The way the transition group works is by adding the class shrink-appear initially to the element that needs to be animated, then additionally adding shrink-appear-active, because our transitionName is "shrink".

If you want to do a leave animation you can do that by just supplying a transitionLeaveTimeout to the transition group and defining 2 new classes, in our example those would be:

.shrink-leave {
  height: 0;

.shrink-leave.shrink-leave-active {
  opacity: 700;
  transition: height 500ms ease-in;

as you can see the leave animation classes are in reverse of our appear animation to provide the opposite effect.