Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use css modules with create-react-app?

According to a tweet by Dan Abramov, CSS modules support is there in create-react-app (CRA). One just needs to give extension of module.css to his stylesheets to enable the feature, but this is not working with me. I am having version 1.1.4 of react-scripts. How can I enable css modules with CRA? Thanks

like image 892
Muhammad Saqib Avatar asked May 08 '18 13:05

Muhammad Saqib


People also ask

Does create-React-app support CSS modules?

CSS Modules are supported with create-react-app out of the box. There is however a catch that you need to know in order to get your CSS Modules working in your create-react-app project.

How do you use modules CSS in React?

To import a CSS Module into the corresponding component, import the css modules stylesheet as styles or [name]Styles : In JSX, use the defined CSS class as a className prop like so: From here, you can add as many other CSS modules you'd like, just remember to import each as a different name.

Where do I put CSS in Create-React-app?

If you are concerned about using webpack-specific semantics, you can put all your CSS right into src/index. css . It would still be imported from src/index. js , but you could always remove that import if you later migrate to a different build tool.


1 Answers

You do not need to eject.

Create React App supports CSS Modules right out of the box as of version 2.

Upgrade to the latest (react-scripts@latest) version.

If you use yarn:

yarn upgrade react-scripts@latest 

If you use npm:

npm install --save react-scripts@latest 

Then you just have to create a file with the extension .module.css

For example:

.myStyle {   color: #fff } 

Then you can use it like so:

import React from 'react' import styles from './mycssmodule.module.css'  export default () => <div className={styles.myStyle}>We are styled!</div> 
like image 136
giraffesyo Avatar answered Sep 25 '22 11:09

giraffesyo