3

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?

2 Answers 2

8

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>
  )
}
Sign up to request clarification or add additional context in comments.

5 Comments

Can I use same className in all files with css module?
yes. because css-module will rename the classname to something like example_dfd23 for it to be unique in the browser.
What if i want to concatenate another class with this css module. Let's say, a bootstrap class. Would i just use template strings like className={row ${styles.example}}
@IbrahimFarooq there is several ways of doing this. one is what you suggested. another is className={["row", styles.example].join(" ")} and then there's a helper package for this called classnames
@Philip I believe even with css modules styles applied to html elements for eg - h1 { color: red } , will still be global and applied to all components? Is that true?
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.