I'm building a react app with React Static Boilerplate.
Each component has a directory structure like this:
MyComponent/
-- MyComponent.css
-- MyComponent.js
-- package.json
and in the MyComponent.js
file, I'm doing a raw import './MyComponent.css'
Let's say my CSS contains something like this:
body { background-color: orange; }
.card { background-color: purple; }
and the render function in my component renders a card:
render() {
return (
<div className="card">Hello World</div>
);
}
The page's body will become orange, but the card will not become purple.
Why is this css not being fully applied to the HTML that is generated?
This error is generated because the compiler is only able to import files from the src folder. Here, the CSS file is saved outside the src folder, so the compiler failed to import it. To make this code work, you just have to save the CSS file inside the src folder.
You can style a React app with plain CSS, in plain . css files, just the same as you can style HTML (or Vue or Svelte or Angular) with plain CSS. Notice how we're import ing the CSS file on line 2, and then we can just use the CSS class on the button via the usual className prop.
To add a global CSS file to your Next. js app, you need to import the file inside pages/_app. js file.
According to the React Static Boilerplate website, they use CSS Modules - this would explain why the body
tag is being respected but the class selector is not.
https://github.com/css-modules/css-modules
try importing the stylesheet like so:
import styles from './MyComponent.css';
The using it in your component like so:
<div className={styles.card}>something!</div>
I had an issue with CSS not being applied, but it wasn't the modules, it ended up being the syntax of applying multiple classes. The syntax below solved the problem
<div className={[styles['col-sm-16'], styles['col-md-10'], styles['col-lg-8']].join(' ')}> some content </div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With