Search code examples
cssreactjscreate-react-appreact-router-dom

Different css stylesheet for routes


I am quite new to react and react-router-dom. The problem is, I am trying to get different layouts for different routes in my application. But instead all of the css files for different routes just imported in one huge conflicting piece.

App looks like this:

<Router>
  < >
    <Navigation />
    <UpButton />
    <Switch>
      <Route path="/" exact component={Home} />
      <Route path="/research" component={Research} />
      <Route path="/publications" component={Publications} />
      <Route path="/student" component={Student} />
      <Route path="/about" component={About} />
    </Switch>
  </>
</Router>

Each component I am rendering looks like this:

import React from 'react';
import './home.scss';

// Utility
import Utility from 'components/utility/Utility';

class Home extends React.Component {
  render() {
    return (
      < >
        <Utility />
      </>
    );
  }
}

export default Home;

Is there a way to import only the specific css file with specific route? Like home.css for '/' route, about.css for '/about' route specifically?

It might be the simple misunderstanding from me, but I really can't find any solution for now.


Solution

  • I recommend to use the following file structure and pattern:

    - components
      - Main.js
      - Utility
        - index.js
        - styles.scss
    - pages
        - HomePage
          - index.js
          - styles.scss
    

    Then specify the component related styles within the component's stylesheet, and the page-realated styles within the page's stylesheet. And use pages for routes, not components. Finally, wrap every component into a specific class selector, and add wrap the belonging sass file into that selector (like .home-page). For this reason, please, use sass instead of css, because you can embed style definitions within each other and use the top one as a "namespace". So the styles will not affect to each other.

    // Main.js
      import HomePage from '../pages/HomePage';
    
      <Switch>
        <Route path="/" exact component={HomePage} />
        <Route path="/research" component={ResearchPage} />
    
    
    // HomePage/index.js
    
      import Utility from './components/Utility';
      import './styles.scss';
      ...
      render(){
        <div className="home-page">
          <Utility />
        </div>
      }
    
    // HomePage/styles.scss    
      .home-page {
        ...
      }
    
    // Utility/index.js
    
      import './styles.scss';
      ...
    
      render(){
        return (
          <div className="utility-comp">
          ...
          </div>
      }
    
    
    // Utility/styles.scss
      .utility-comp {
        ...
      }