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.
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>
)
}
}
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>
);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With