How to load only needed CSS per component (React js)

Viewed 635

I've started to code my first React app and it's awesome, but I can't figure out how to manage css files per-component(so the actual CSS won't load if it is not necessary).

React with webpack(correct me if I'm wrong please) wraps the project in such a way that at every given moment the app loads only what it needs(in terms of JS).

So if I have my main App component with only two buttons visible: btn-01 and btn-02, and inside of this component I have another two: component-01 and component-02, and they are hidden till the corresponded button is clicked(btn-01 for component-01), these components won't be loaded until the actual button is clicked(am I getting this right?), however this is not the same with css as I can tell, because I see the css of each of these(component-01 and component-02) components loaded right away the App is loaded, even though none of the buttons are clicked.

I'm not a big fan of inline styling, but I did test it with css module, but the result is the same in this aspect. So I'm not even sure if this is possible to implement in an easy way.

Here's a code, so perhaps I'm not implementing it correctly, but please don't mind the none-DRY code etc.

So as you may see, the style of Component-01 and -02 are loaded even though there is no need for them at the moment(none of the button is pressed).

App.js

import React, { Component } from "react";
import "./App.css";
import Component_01 from "./Component-01/Component-01";
import Component_02 from "./Component-02/Component-02";

class App extends Component {
  state = {
    isComponent_01: false,
    isComponent_02: false,
  };

  toggleComponent01 = () => {
    this.setState({
      isComponent_01: !this.state.isComponent_01,
    });
  };

  toggleComponent02 = () => {
    this.setState({
      isComponent_02: !this.state.isComponent_02,
    });
  };

  render() {
    let showComponent_01 = null;
    if (this.state.isComponent_01) {
      showComponent_01 = <Component_01 />;
    }

    let showComponent_02 = null;
    if (this.state.isComponent_02) {
      showComponent_02 = <Component_02 />;
    }

    return (
      <div className="App">
        <button className="btn-01" onClick={this.toggleComponent01}>
          Btn-01
        </button>
        <button className="btn-02" onClick={this.toggleComponent02}>
          Btn-02
        </button>

        {showComponent_01}
        {showComponent_02}
      </div>
    );
  }
}

export default App;

Component-01.js (and Component-02.js, just with -02.js)

import React from "react";
import style from "./Component-01.module.css";

function App() {
  return <div className={style["component-01"]}>Component-01</div>;
}

export default App;
0 Answers
Related