Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addClass and removeClass react

Tags:

reactjs

I want to check that the target element contains a class or not. if not add the class and if yes then remove the class.

class Hello extends React.component{
  addActiveClass(e){
     if(e.target.classList.contains("active")){
         //I wanna to add active class to e.target
     }else{
         //I wanna to remove active class from e.target
         //I wanna to do something like e.target.classList.removeClass("atcive");
     }
  }

  render() {
       <div className="red green blue" onClick={this.addActiveClass}>Hello World</div>
       <div className="red green blue" onClick={this.addActiveClass}>Good Bye World</div>

  }
}

I wanna to add and remove class to only target element not the other elements.

like image 814
Sourabh Banka Avatar asked Feb 27 '18 17:02

Sourabh Banka


2 Answers

You can make use of the state to store the active div and then conditionally add active class to it

class Hello extends React.component{
  state = {
    active: ''
  }
  addActiveClass(e){
      const clicked = e.target.id
      if(this.state.active === clicked) { 
          this.setState({active: ''});
      } else {
          this.setState({active: clicked})
     }
  }

  render() {
     return (
   <div>
<div className={`red green blue ${this.state.active === "first"? 'active': ''}`} id="first" onClick={this.addActiveClass}>Hello World</div>
<div className={`red green blue ${this.state.active === "second"? 'active': ''}`} id="second" onClick={this.addActiveClass}>Good Bye World</div>
  </div>
     )
  }
}
like image 114
Shubham Khatri Avatar answered Nov 09 '22 11:11

Shubham Khatri


My answer is similar to others but I love this part what I do here:

class ChildComp extends React.Component{
   super(props);
   this.state = {
      active: false
   }

   toggle(e){
      this.setState({active: !this.state.active});
   }

   render(){
     return(
        <div 
          className={classNames(
            "red green blue", 
            this.state.active ? "active" : "" 
          )}
          onClick={e => this.toggle(e)}
        >
          {this.props.text}
        </div>
     );
   }
}
class Hello extends React.Component{
   render(){
      return(
         <div>
            <ChildComp text="Hello World"/>
            <ChildComp text="GoodBye World"/>
         </div>
      );
   }
}
like image 4
Yash Thakur Avatar answered Nov 09 '22 11:11

Yash Thakur