Search code examples
cssreactjsreact-routercreate-react-app

React Components using css files that are not imported to them


Basically, I am using different css files for a reason. My problem is that when I am styling something in one css file, it affects some other components I have, not only the one where I import this css file.

I think the problem is with react-router. I think it shares css files from every component i import to it. When I stop using a component in router, then its css files are not shared.

But how do I do routes different way? I need to import all components to router to have links to my pages.

I also tried to put routes into seperate files, it didn't help as well.

That's how my file with routes looks like:

import React, { Component } from 'react';
import {
  BrowserRouter as Router,
  Route
} from 'react-router-dom';

import './App.css';
import LoginPage from '../pages/LoginPage.js';
import Navbar from './Navbar.js';
import MainPage from '../pages/MainPage.js';
import SportsfieldsListPage from '../pages/SportsfieldsListPage.js';
import MyProfilePage from '../pages/MyProfilePage.js';
import SingleObjectPage from '../pages/SingleObjectPage.js';
import ConfirmPage from '../pages/ConfirmPage.js';
import AdminPage from '../pages/AdminPage.js';

class App extends Component {
  render() {
    return (
      <Router>
        <div className="container">
        <Navbar />
          <Route exact path="/" component={MainPage} />
          <Route exact path="/listaBoisk" component={SportsfieldsListPage} />
          <Route exact path="/LoginPage" component={LoginPage} />
          <Route exact path="/MyProfilePage" component={MyProfilePage} />
          <Route path="/object/:id" component={SingleObjectPage}/>
          <Route path ="/confirm/:id/:value" component={ConfirmPage}/>
          <Route path ="/adminPage" component={AdminPage}/>
        </div>
      </Router>
    );
  }
}

export default App;

Solution

  • You can use CSS modules for your project CSS Modules.Using this, unique class names are generated.

    If you dont want to do this, then u you can use CSS class nesting, for eg: For Main Page Component

    <div className="main-page">
     <div className="title">Main Page</div>
    </div>
    

    use css like this:

     .main-page .title{
      color:red;
     }
    

    Similarity for other components use css like this

     .login-page .title{
      color:green;
     }
    

    This way, your css styles will not get mixed up