adding-a-css-modules-stylesheet.md 1.75 KB
Newer Older
1
2
---
id: adding-a-css-modules-stylesheet
Dan Abramov's avatar
Dan Abramov committed
3
title: Adding a CSS Modules Stylesheet
4
sidebar_label: Adding CSS Modules
5
6
7
8
9
10
---

> 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]`.

11
> **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`.
12
13
14

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/).

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

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

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

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

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

```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>;
  }
}
```

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

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.