Reputation: 647
Hello I'm using React to build a website and I want to use .CSS files for my CSS and I'm using import './example.css' in my component file. Example:
import React from 'react';
import 'Home.css';
const Home = () => {
return (
<div className="example">
Hi
</div>
)
}
and if i create another page but don't import this CSS file, I get the styles on my other page other page:
import React from 'react';
const About= () => {
return (
<div className="example">
Hi
</div>
)
}
Any reason and solution for this?
Upvotes: 3
Views: 7808
Reputation: 156
When importing a css file like you've done it will be injected into the project and not just into the component you're importing it from.
What you're looking for is css-modules (adding css-modules using create-react-app)
import React from 'react';
import styles from 'Home.css';
const Home = () => {
return (
<div className={styles.example}>
Hi
</div>
)
}
Upvotes: 8
Reputation: 1047
The reason is that you are using the same class in both of your components.
Doing import 'Home.css'
does not encapsulate .css
only for that component, all of the .css
gets bundled together so it ends up overwriting styles somewhere down the line.
For each of the components, you can specify a unique className
on top of your component, and use that class to style only that component.
.home-container .header { ... }
You can also make one global .css
part to put styles that you want to keep using throughout the whole app.
Upvotes: 2