简体   繁体   中英

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!

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.

this is what I usually do. I make a variable that holds the class names and put this variable inside my jsx. Something along the lines of:

magic: function() {
  var myClass = this.state.cartClasses;

  if (condition) {
    this.setState({ cartClasses: 'class1' });
  } else {
    this.setState({ cartClasses: 'class2' });
  }  

  return (
    <div className={myClass}>
      hello world
    </div>
  );
}

Hope this helps :)

There is a javascript utility called classnames which can be used to join multiple classnames.

This is a link to their github page This gives more clarity and I have found it more intuitive to understand. For example, your code could be written as

var cartClasses = classNames('order-wrap',{'cart-out':  newTotalClean!=0});

The above says that by default,there will be a class called order-wrap assigned and only if the condition is met,the other class is assigned.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM