This tutorial is an element 2 of two within the sequence.
CSS Modules are some of the well-liked methods for styling React elements. Whether or not you’re utilizing solely CSS or a extra superior pre-processor like SASS, it does not matter for CSS Modules: You possibly can write all these types in your model sheet information subsequent to your React elements.
Since we’re build up on high of a customized React + Webpack utility, it wants some arrange from our facet earlier than we are able to begin utilizing CSS Modules in React. I need to thank Arpit Batra for displaying use the way it works.
Observe: If you’re utilizing create-react-app, simply observe this Create React App with CSS Modules tutorial. It comes with CSS Modules out of the field. If you’re utilizing your customized React + Webpack setup, possibly from a earlier tutorial of mine, maintain studying for organising CSS Modules in your customized React challenge.
First, we’d like some extra loaders for Webpack. These loaders allow Webpack to bundle CSS information as effectively:
npm set up css-loader model-loader --save-dev
And second, in your webpack.config.js file, add the brand new loaders for decoding CSS information:
module.exports = {
...
module: {
guidelines: [
...
{
test: /.css$/i,
exclude: /node_modules/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: true,
},
},
],
},
],
},
...
};
That is already it for the CSS Modules setup in Webpack. Subsequent, you may outline your first CSS file. Let’s title it src/model.css:
.title {
coloration: blueviolet;
}
Then you may import the CSS file in certainly one of your React elements. Afterward, you’re already ready to make use of the CSS class outlined within the CSS file in your React element. Simply import it and use its outlined CSS class as className prop in your React element.
import React from 'react';
import types from './model.css';
const App = ({ title }) => (
<div className={types.title}>{title}</div>
);
export default App;
From right here you are ready so as to add extra CSS information subsequent to your React elements. Usually one would use one model file for every React element. On this CSS file, you’re free so as to add as many CSS courses as you might want to model your React element. Merely import the types from the CSS file and use them as proven earlier than in your React element.