Search code examples
javascriptcssreactjscss-modules

CSS Modules vs. normal CSS to change background of page in React


Edit: The accepted answer helped me arrive at the problem. It is correct so I accepted it. But I was importing my module which included the body tag and not using it.

import styles from "./App.module.css"; //Includes a body tag

styles isn't used anywhere in the code, so I don't think WebPack was including it. If I did anything with that module, the body tag was included and it worked. <div className={styles.anything}> allowed the body CSS to be included.

This could be due to Typescript as the answerer said in a comment.


I used create-react-app to make an app. I'm using CSS Modules in my components. I'm trying to figure out how to use CSS Modules to make the overall background of the page a different color.

I want to apply background-color: #121212; to the entire background.

I'm trying to figure out how to apply that style, and right now it seems it would need to be applied to the body tag.

Any styles applied to App.tsx only affect the container which that component takes up (The background is colored only to the bottom of the App component and white below it)

Right now index.css contains

body {
  ...
  background-color: #121212;
}

This works fine. I'd like to use modules though, and I don't know how I can import that style to work.

Where would I import a style on the index.tsx file created by create-react-app with Webpack.

ReactDOM.render(<App />, document.getElementById('root'));


Solution

  • Open up one of your .module.css file, and paste this:

    body {
        background-color: red;
    }
    

    CSS modules, just like CSS files, are imported and applied globally by Webpack.

    If you want to create another .module.css just for the body tag, then you can create a new module, for example, MyModule.module.css and paste the above code. Then, import this new module to one of your tsx file.

    You don't need to do anything with it, just import like this:

    import myStyles from "./MyModule.module.css";