I have a React app in VS Code. I want to set a different background color for each component. However, even though each component only imports its respective CSS file, it still applies CSS from other files that are not imported. How can I fix this so that CSS files that are not imported do not interfere with the ones I import into each component?
I’ve tried to use js functions instead to change the color but it seems to be an unnecessary solution and I guess that there is a css related solution instead.
1
Yes, I have faced this issue a lot.
This usually happens when the same className is used or applied to the tags(html tags)
I just learnt that CSS files are global by default and the rules defined for one component or the CSS of one file may be applied to other files too. Also, the styles can cascade down from the parent components to child components unintentionally, so make sure to use different class names every time in your React JS projects.
Apart from this, you can use CSS Modules, which is a better solution overall
Name your CSS files as: Cssfilename.module.css
.container{
background-color: red;
color: yellow;
}
In your ReactJS Component:
import React from "react";
import styles from "./Cssfilename.module.css";
const Component = () => {
return (
<div className={styles.container}>
Some Random Text in Yellow color
</div>
);
};
export default Component;
By using CSS Modules, you can ensure that the styles are scoped to the component, preventing unwanted interference and making your CSS more maintainable.
Manobendra Mandal is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2