1//toggle css class in react using mouse clicks
2//solution
3class foo extends Component {
4 constructor(props){
5 super(props);
6 this.state={
7 isToggle:false
8 }
9 }
10 render() {
11 return (
12 <div className={this.state.isToggle ? "myClass":null}
13 onClick={()=>{this.setState({isToggle:!this.state.isToggle});}}>
14 <div className="box">
15 </div>
16 </div>
17 );
18 }
19}
20//or in more elegant way
21
22class foo extends Component {
23 constructor(props){
24 super(props);
25 ////////////////////////////////////////
26 // this variable will be used to know when should your progam use the class or not
27 this.state={
28 isToggle:false
29 }
30////////////////////////////////////////
31 }
32 render() {
33 return (
34////////////////////////////////////////
35 // if (this.state.isToggle) then "myClass" else null
36 <div className={this.state.isToggle ? "myClass":null}
37////////////////////////////////////////
38////////////////////////////////////////
39 // when the current div is clicked negate isToggle
40 onClick={()=>{this.setState({isToggle:!this.state.isToggle});}}>
41 <div className="box">
42 </div>
43 </div>
44////////////////////////////////////////
45 );
46 }
47}