I am trying to figure out how to toggle an active class onClick
to change CSS properties.
I have taken many approaches, and read many SO answers. Using
I would prefer using "&&" -operator on inline if-statement. In my opinnion it gives cleaner codebase this way.
Generally you could be doing something like this
render(){
return(
<div>
<button className={this.state.active && 'active'}
onClick={ () => this.setState({active: !this.state.active}) }>Click me</button>
</div>
)
}
Just keep in mind arrow function is ES6 feature and remember to set 'this.state.active' value in class constructor(){}
this.state = { active: false }
or if you want to inject css in JSX you are able to do it this way
<button style={this.state.active && style.button} >button</button>
and you can declare style json variable
const style = { button: { background:'red' } }
remember using camelCase on JSX stylesheets.
you can add toggle class or toggle state on click
class Test extends Component(){
state={
active:false,
}
toggleClass() {
console.log(this.state.active)
this.setState=({
active:true,
})
}
render() {
<div>
<div onClick={this.toggleClass.bind(this)}>
<p>1</p>
</div>
</div>
}
}