Danny Dyer Danny Dyer - 2 months ago 9
React JSX Question

proper way of adding/removing classes in React

I'm a React newbie and have a question!

Im posting this because I haven't been able to find a clear answer on what the best method is for adding/ removing classes to HTML in React. I have created my first React app and came to the point where I wanted to start animating some of the elements of my app by adding/ removing classes when a certain action happens.

Here is what I have done:

I have passed the elements class that I want to animate through a state. The state is given an initial value like so:

getInitialState: function() {
return {
cartClasses:"order-wrap"
}
}


Then I have passes down the state to a child component which receives the state and implements the cart classes like so:

<div className={this.props.cartClasses}>


In one of my functions I have the following if statement:

newTotalClean != 0 ? this.setState({cartClasses:"order-wrap cart-out"}) : this.setState({cartClasses:"order-wrap"});


Basically it evaluates one of my variables called newTotalClean and if it doesn't equal 0 it updates the state of cartClasses to "order-wrap cart-out" thus adding an extra class that contains CSS animation effects.

Usually I would use jQuery Add/removeClass() but i'm trying to restrict myself from using that and do it in a more React way, not sure if storing classes in a state is the best method or not?

Thanks for your help!

Answer

I suggest you use ReactCSSTransitionGroup. Instead of setting the className, you set the transition name like the following:

<ReactCSSTransitionGroup 
    transitionName="example" 
    transitionEnterTimeout={500} 
    transitionLeaveTimeout={300}
>
    ... some code here ..
</ReactCSSTransitionGroup>

See this page to learn more about Animations in React.