3

I have two modules in my application :-

- main module
- admin module

I want to maintain different styling for them but the css for admin module is overriding that of main

App.js

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

//styles
import './style/bootstrap/bootstrap.scss';

//apps
import Mainapp from './mainapp/Mainapp';
import Admin from './admin/Admin';

const MainappContainer = () => (
  <div className="App">
    <Mainapp />
  </div>
);

const AdminContainer = () => (
  <div className="App">
    <Admin />
  </div>
);

class App extends Component{
  render(){
    return (
      <Router>
        <Switch>
            <Route exact path="/admin" component={AdminContainer}/>
            <Route component={MainappContainer}/>
        </Switch>
      </Router>
    )
  }
}

export default App;

Mainapp.js

import React, {Component} from 'react';

import '../style/custom-style.scss';

class Mainapp extends Component{
    render(){
      return (
        <div>
            Main App
        </div>
      )
    }
  }

  export default Mainapp;

Admin.js

import React, {Component} from 'react';

import '../style/admin-styles/admin-style.scss';

class Admin extends Component{
    render(){
      return (
        <div>
            Admin App
        </div>
      )
    }
  }

export default Admin;

The styles I specify on admin-style.scss is getting applied even for main app.

What am I doing wrong?

Stacy J
  • 2,721
  • 15
  • 58
  • 92

1 Answers1

3

I am assuming you are using Webpack to bundle your application? If yes, modern module bundlers such as Webpack will bundle your all your assets (js, css, images, etc) into one giant file (if advanced Webpack techniques such as code splitting is not used). That's why you are seeing two styles are applied.

One module's style is overriding the other's style, this implies you have CSS global naming collision, meaning you have CSS selectors with the same name, but applying different styles. I would recommend using CSS Modules to avoid global style collisions.

Zico Deng
  • 645
  • 5
  • 14
  • Yes CSS Modules does create a local scope, however, css for both loads on the page irrespective of if it is mainapp or adminapp. Is there any way we can only load mainapp css when mainapp loads. The css for admin app is redundant for mainapp as it will have different style guide. To achieve this, will I need to create a different react app for admin or as you said use code splitting in webpack. – Stacy J Sep 04 '19 at 11:55
  • 1
    Yes, code splitting is the way to go! This is a good read: https://itnext.io/react-router-and-webpack-v4-code-splitting-using-splitchunksplugin-f0a48f110312 – Zico Deng Sep 04 '19 at 15:18