Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Some CSS loaded into React app are not applied

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?

like image 774
Kristian Avatar asked Apr 13 '17 18:04

Kristian


People also ask

Why is my CSS not being applied React?

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.

Can you use regular CSS with React?

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.

Where do I put the CSS file in Create React app?

To add a global CSS file to your Next. js app, you need to import the file inside pages/_app. js file.


2 Answers

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>

like image 138
Toby Avatar answered Oct 08 '22 15:10

Toby


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>
like image 2
user1169692 Avatar answered Oct 08 '22 14:10

user1169692