Bootcamp
Search…
📅
Course Schedule
0: Language and Tooling Teaching Guide
1: Frontend Basics Teaching Guide
2: Backend Basics Teaching Guide
3: Backend Applications Teaching Guide
4: Backend Structure Teaching Guide
5: Full-Stack Applications Teaching Guide
6: Frontend Infrastructure Teaching Guide
7: React Teaching Guide
8: Advanced React Teaching Guide
9: Advanced Topics Teaching Guide
🧮
Algorithms Teaching Guide
💼
Interview Prep Teaching Guide
☺
User Experience Teaching Guide
8.6: Styled Components
Create React App describes how to use CSS as JavaScript inside your React app: https://create-react-app.dev/docs/adding-a-css-modules-stylesheet​

Button.module.css

1
.error { background-color: red; }
Copied!

Button.js

1
import React, { Component } from 'react';
2
import styles from './Button.module.css'; // Import css modules stylesheet as styles
3
​
4
class Button extends Component {
5
render() {
6
// reference as a js object
7
return <button className={styles.error}>Error Button</button>;
8
}
9
}
Copied!

CSS Class Logic

We can use this syntax to conditionally apply a class.
We'll create a component that applies a class if an email is valid or not.

emailInput.js

1
import EmailValidator from 'email-validator';
2
​
3
import styles from './emailInput.module.css'; // Import css modules stylesheet as styles
4
​
5
export default function EmailInput() {
6
​
7
// what is currently entered in the input
8
const [email,setEmail] = useState(null);
9
​
10
// wether or not the current input is a valid email
11
const [isValidEmail,setValidEmail] = useState(null);
12
​
13
const handleEmailChange = (event) => {
14
15
// check to see if the input is a valid email
16
if (EmailValidator.validate(event.target.value)) {
17
setValidEmail(true);
18
} else {
19
setValidEmail(false);
20
}
21
​
22
setEmail(event.target.value);
23
};
24
​
25
let inputClass;
26
​
27
// check the state variable to see if a class should
28
// be applied on the input
29
if (isValidEmail === true) {
30
inputClass = styles.valid;
31
} else if (isValidEmail === false) {
32
inputClass = styles.invalid;
33
}
34
​
35
return (
36
<div>
37
<p>Is valid email: {`${isValidEmail}`}</p>
38
<input
39
className={inputClass}
40
value={email}
41
onChange={handleEmailChange}
42
/>
43
</div>
44
);
45
}
Copied!

emailInput.module.css

We give the CSS file a name with module in it that will tell CRA to process this file.
1
input:focus {
2
outline: none;
3
}
4
​
5
input {
6
border: 1px solid black;
7
}
8
​
9
.valid {
10
border: 1px solid green;
11
}
12
​
13
.invalid {
14
border: 1px solid red;
15
}
Copied!
Notice that the class names themselves are transformed by Webpack in the browser version of the CSS.
Full working example here: https://codesandbox.io/s/rough-sky-yn6jc​

Comparison

Here is a link that compares all the different ways that React has to do CSS.
CSS Modules are the method that is supported in Create React App out of the box.
Last modified 2mo ago