How to add and remove classes in ReactJS with push and state.
A Pen by Jorge Rodriguez on CodePen.
<div id="root"> | |
</div> |
How to add and remove classes in ReactJS with push and state.
A Pen by Jorge Rodriguez on CodePen.
class App extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = {addClass: false} | |
} | |
toggle() { | |
this.setState({addClass: !this.state.addClass}); | |
} | |
render() { | |
let boxClass = ["box"]; | |
if(this.state.addClass) { | |
boxClass.push('green'); | |
} | |
return( | |
<div className={boxClass.join(' ')} onClick={this.toggle.bind(this)}>{this.state.addClass ? "Remove a class" : "Add a class (click the box)"}<br />Read the tutorial <a href="http://www.automationfuel.com" target="_blank">here</a>.</div> | |
); | |
} | |
} | |
ReactDOM.render(<App />, document.getElementById("root")); |
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react.js"></script> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react-dom.js"></script> |
.box { | |
display: block; | |
width: 200px; | |
height: 200px; | |
background-color: gray; | |
color: white; | |
text-align: center; | |
vertical-align: middle; | |
cursor: pointer; | |
} | |
.box.green { | |
background-color: green; | |
} |