I’m developing a React application and facing an issue with CSS rendering. My application includes two main components, <Product />
and <MainPage />
, each referencing their own CSS files (product.css
and main.css
respectively). However, I’m encountering a problem where both CSS files are being applied globally, leading to style conflicts between the two pages.
Here’s a simplified version of my App component:
import React from 'react';
import ReactDOM from 'react-dom/client';
import Header from './header.js';
import { useState } from "react";
import Product from './product.js';
import MainPage from './main.js';
function App() {
const [selectedProduct, setSelectedProduct] = useState(null);
return (
<div>
<Header />
{selectedProduct ? <Product product={selectedProduct} /> : <MainPage onSelectProduct={setSelectedProduct} />}
</div>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
Each component (<Product />
and <MainPage />
) imports its CSS file at the top of its respective JS file. I’m trying to ensure that main.css is only applied when the component is rendered and product.css is only applied when the component is rendered. How can I achieve this isolation so that each page only uses its respective CSS without affecting the other?
I’ve considered using CSS modules but I am looking for a different approach. Any advice or recommendations on how to resolve this issue would be greatly appreciated.
2
Answers
In React, there are three ways to add adding css to the components. Try creating a new CSS file for each of the pages and importing it into each of the components.
You should KISS (Keep it Sweet and Simple) –
CSS conflicts are painful, so to avoid this conflict you should make sure to import your css file only to the specific component like below –
MainPage component –
Product component –
Your import location can be different depending on where the css file exists.
Another way to avoid conflict is to have unique container names on your each component and apply the css in nested format like –
This way you can create a single css file and import it on your App() component with no conflicts even if your child tags under the container tags has same names.
App.css –
App.js –