Skip to main content

5.04 Setting Class Names Dynamically

App.css
.App {
text-align: center;
}

.red {
color: red;
}

.bold {
font-weight: bold;
}
App.js
    ...
style.backgroundColor = "red";
}

const classes = [];
if (this.state.persons.length <= 2) {
classes.push("red"); // classes = ['red]
}
if (this.state.persons.length <= 1) {
classes.push("bold"); // classes = ['red', 'bold']
}

return (
<div className="App">
<h1>Hi, I'm a React app!</h1>
<p className={classes.join(" ")}>This is really working!</p>
<button style={style} onClick={this.togglePersonsHandler}>
Toggle Persons
</button>
...