elham rajai rad
elham rajai rad

Reputation: 33

CSS Modules in React.JS

I'm using version 3 of the create-react-app package. But my styles don't apply

import style from './App.css'

Upvotes: 1

Views: 941

Answers (6)

starterProgrammer
starterProgrammer

Reputation: 301

For example we have to files like

Button.module.css

.error {
  background-color: red;
}

another-stylesheet.css

.error {
  color: red;
}

**How to Use? **

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 (
     <div>
         <button className={styles.error}>Error Button</button> // Use 
          Module css 
         <button className="error">Error Button</button> //normal css 
         file
     </div>
   );
 }}

Upvotes: 0

hakobpogh
hakobpogh

Reputation: 677

If you want to apply styles easily to your existing code, you can use the patch-styles package. See the example of usage in StackBlitz. It's introducing a more declarative way for applying styles you need to wrap your code with <PatchStyles classNames={style}> where style is the default import from the style module.

Upvotes: 0

user9408899
user9408899

Reputation: 4540

Save your css file with module extention.

App.module.css

Then import it like this:

import style from './App.module.css'

Finally, apply your styles like this:

<div className={style.container}> Hello World! </div>

Upvotes: 2

alisasani
alisasani

Reputation: 2968

Please read this link talking about adding a stylesheet to CRA. https://create-react-app.dev/docs/adding-a-stylesheet/

In summary, you should write import './App.css'

Upvotes: 2

seunggabi
seunggabi

Reputation: 1820

Try this.
import './App.css';
add your code.

Upvotes: -1

Pedro Filho
Pedro Filho

Reputation: 25

I guess you just want to import and apply the styles, right?

If you want to just use the css you can just import it, like this:

import './App.css'

And it will be applied!

Upvotes: -1

Related Questions