×
  • React – The Complete Guide (incl. React Router 4 & Redux)

  • 32 – Enable and Use CSS Modules In React

    Lesson List
    [ Enable and Use CSS Modules In React, Enable and Use CSS Modules In React ]

    Over the last lessons, you learned about radium one third part package which is very popular and which allows you to use inline styles with features like media queries.
    Now that’s one way of scoping your styles, being able to easily edit them and still use features like media queries, It’s not the only way through.

    – Wouldn’t it be great if a CSS file like our Person.CSS that could be scoped in the Person.js component file so that whichever styles we define in Person.css could be imported and assigned to the elements in the component and wouldn’t override styles and other components or other parts of the app.

    CSS Modules In React

    That is possible, and it is possible in the setup we use here. We can use a feature named CSS modules and I want to show you how to use set.
    First of all get rid of the the radium removing the style setup in components and from the exports method with radium in both Person.js and App.js file.
    Now want to Handel everything from scoped CSS files and to do that we need to tweak the build configuration of our project.
    I have mentioned earlier in this course that we are using react-scripts (you can see in package.json) that this is a package which exposes the whole build workflow to us and we can’t really add to the configuration.

    React eject command

    Thankfully there is a command which gives us access to the configuration through.

    eject : you can NPM run eject, everything is managed for me but I can edit the configuration project.
    package.json
    
    ...
      "scripts": {
        "start": "react-scripts start",
        "build": "react-scripts build",
        "test": "react-scripts test",
        "eject": "react-scripts eject"  // gives access to configuration
      },
    ...
    

    Now there wont be a way back but it shouldn’t break it will still work in the same way it did before, but then you can then edit the configuration.

    Unlock feature of CSS modules

    Of course this should be done with care because you don’t want to break the setup.

    Important:
    One important ote if you are using GIT to track you changes make sure you add and commit all changes before you run the eject command it will not work otherwise.

    open the project folder in terminal and then run the following command.

    Bash
    
    npm run eject
    

    You will be prompt if we want to do that because we cant’t go back.
    Now you will see some new folders i.e. the scripts and the config folder.

    Configuring webpack config file

    However for us intreasting in the config folder is the webpack.config.js
    Well since web pack is the one responsible for this, web pack is the place where we can now also adjust the way we handle CSS files and where we can unlock extra features I was referring to using CSS modules.
    so inside the webpack.config.js file find for test: cssRegex, and add update the code as mention below.

    webpack.config.js
    
    ...
    {
      test: cssRegex,      // find for this
      exclude: cssModuleRegex,
      use: getStyleLoaders({
        importLoaders: 1,
        sourceMap: isEnvProduction && shouldUseSourceMap,
        // Update this below two lines.. Or else it wont work
        modules: true,
        getLocalIdent: getCSSModuleLocalIdent,
      }),
      ...
    }
    ...
    

    After that one important thing changed, when we import App.css it will now scope CSS classes in the App.css file to that App component where we imported.
    We also need to tweak that import statement

    App.js
    
    import AppClasses from './App.css';
    

    And will assign that class into our return statement.

    App.js
    
    import AppClasses from './App.css';
    ...
    return (
      <div className={AppClasses.App}> {/* Javascript Object containing the CSS classes from App.css */}
    		 ...
    	</div>
    );
    ...
    

    Just what we did before but now using totally different technique behind the scenes.

    CSS loader( in webpack.config.js ):
    The CSS loader of course does not so any real magic here, instade what is happening here is that CSS loader transform the CSS class name that we setup in the CSS file into a unique one using the local ident name pattern we setup in the web pack.

    And for the similar for the paragraph which we were pushing classes so there we can simply push the classes which we imported.

    App.js
    
    import AppClasses from './App.css';
    ...
    const classes = [];
    if (this.state.persons.length <= 2) {
    	classes.push(AppClasses.red);
    }
    if (this.state.persons.length <= 1) {
    	classes.push(AppClasses.bold);
    }
    return (
    	<div className={AppClasses.App}>
    		{/* Javascript Object containing the CSS classes from App.css */}
    		<button style={style} onClick={this.togglePersonsHandler}>
    			Switch Name
    		</button>
    		<p className={classes.join(' ')}>Some Random Paragraph</p>
    		{persons}
    	</div>
    );
    ...
    
    Note:
    Even after following all the steps if it dosent work, just simply the development server. Because if we chaged the configuration as we did we have to that.

    As you find that our App.css classes are implemented but the Person.css styles are lost, thats normal because we haven’t adjust the component yet.

    Adjusting Person componet

    In the person component we also follow the same pattern which we did for App.js file.

    src/Person/Person.js
    
    import React from 'react';
    import PersonClasses from './Person.css';
    const person = props => {
    	return (
    		<div className={PersonClasses.Person}>
    		...
    		</div>
    	);
    };
    export default person;
    

    And now we are back to the old setup with our card look. Now finally lets make that media query and that :hover state work too with the CSS modules well do this in the next lesson.

    React introduction
    React Component
    Enable and Use CSS Modules In React

    One response to “32 – Enable and Use CSS Modules In React”

    1. Ahtezaz shah says:

      AFTER THIS I GET AN ERROR
      ./src/index.css (./node_modules/css-loader/dist/cjs.js??ref–6-oneOf-3-1!./node_modules/postcss-loader/src??postcss!./src/index.css)
      ValidationError: Invalid options object. CSS Loader has been initialized using an options object that does not match the API schema.
      – options has an unknown property ‘getLocalIdent’. These properties are valid:
      object { url?, import?, modules?, sourceMap?, importLoaders?, localsConvention?, onlyLocals?, esModule? }

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    This site uses Akismet to reduce spam. Learn how your comment data is processed.

    We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
    Accept