Skip to main content

5.10.1.0 CSS Modules Usage

After adding the configuration (see the previous page) you'll get an object and properties to access the CSS rules.

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

.red {
color: red;
}

.bold {
font-weight: bold;
}

.Button {
background-color: green;
color: white;
font: inherit;
border: 1px solid blue;
padding: 8px;
cursor: pointer;
}

.Button:hover {
background-color: lightgreen;
color: #333;
}
App.js
import React, { Component } from "react";
import classes from "./App.css";
import Person from "./Person/Person";

...

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

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

export default App;