0

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
  • Please provide enough code so others can better understand or reproduce the problem. Commented Jul 16, 2024 at 19:02

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This requires that the bundling system, etc. has been configured to use CSS modules.
Thanks for your answer! But how can I apply modules to the <body> ? My problem currently is that I can't change the background color of the <body> to be different from component to component, unless I put !important it will stay white and if I use important it apllies it to every component.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.