Skip to content

Instantly share code, notes, and snippets.

@dumpofmemory
Created March 17, 2019 18:19
Show Gist options
  • Save dumpofmemory/f78e7c9177041d13c05f6d8e2c160276 to your computer and use it in GitHub Desktop.
Save dumpofmemory/f78e7c9177041d13c05f6d8e2c160276 to your computer and use it in GitHub Desktop.
ReactJS: Adding and removing classes
<div id="root">
</div>
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment