adding-a-css-modules-stylesheet.md 1.72 KB
Newer Older
1
2
3
4
5
6
7
8
9
---
id: adding-a-css-modules-stylesheet
title: Adding a CSS Modules Stylesheet
---

> Note: this feature is available with `react-scripts@2.0.0` and higher.

This project supports [CSS Modules](https://github.com/css-modules/css-modules) alongside regular stylesheets using the `[name].module.css` file naming convention. CSS Modules allows the scoping of CSS by automatically creating a unique classname of the format `[filename]\_[classname]\_\_[hash]`.

10
> **Tip:** Should you want to preprocess a stylesheet with Sass then make sure to [follow the installation instructions](/docs/adding-a-sass-stylesheet) and then change the stylesheet file extension as follows: `[name].module.scss` or `[name].module.sass`.
11
12
13

CSS Modules let you use the same CSS class name in different files without worrying about naming clashes. Learn more about CSS Modules [here](https://css-tricks.com/css-modules-part-1-need/).

14
## `Button.module.css`
15
16
17
18
19
20
21

```css
.error {
  background-color: red;
}
```

22
## `another-stylesheet.css`
23
24
25
26
27
28
29

```css
.error {
  color: red;
}
```

30
## `Button.js`
31
32
33
34
35
36
37
38
39
40
41
42
43
44

```js
import React, { Component } from 'react';
import styles from './Button.module.css'; // Import css modules stylesheet as styles
import './another-stylesheet.css'; // Import regular stylesheet

class Button extends Component {
  render() {
    // reference as a js object
    return <button className={styles.error}>Error Button</button>;
  }
}
```

45
## Result
46
47
48
49
50
51
52
53
54

No clashes from other `.error` class names

```html
<!-- This button has red background but not red text -->
<button class="Button_error_ax7yz"></div>
```

**This is an optional feature.** Regular `<link>` stylesheets and CSS files are fully supported. CSS Modules are turned on for files ending with the `.module.css` extension.