Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 309
Isard Avatar asked Nov 23 '25 06:11

Isard


1 Answers

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

like image 73
Gautam Naik Avatar answered Nov 28 '25 04:11

Gautam Naik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!