Getting Started with Styling with CSS Modules in React
In this and subsequent lessons, we will look at another modern and effective approach to styling React components - using CSS modules.
CSS modules in this approach are separate compiled CSS files in which class and animation names are in local scope, which avoids conflicts between class names from different components.
First, let's create and launch our simple React application buttons. To do this, create an empty folder test, go into it and write the following commands in the terminal:
npx create-react-app buttons
cd buttons
npm start
If you have a fresh version of React, that is, it supports Create React App v2 and higher, then you don’t need to do any additional settings, since in this case CSS modules will be supported automatically. To check, look in package.json, if the react-scripts dependency is version 2.x.x and higher, then everything is fine. Otherwise, update your React.
Our CSS modules styled application will contain three buttons.
CSS We will name the files, following the convention, as follows: [name].module.css.
Let's now create a folder components in src, and add a file Buttons.module.css with CSS styles for our buttons:
.btn1 {
background-color: orange;
border: 2px solid brown;
color: white;
}
.btn2 {
background-color: red;
border: 2px solid green;
color: yellow;
}
.btn3 {
background-color: brown;
border: 2px solid yellowgreen;
color: orange;
}
Also in the components folder, create an empty React component file Buttons.js, but don't touch the generated file App.js for now, we'll deal with it later!
In Buttons.js we must import the file with CSS styles, and also apply these styles to each button using the class attribute:
import styles from "./Buttons.module.css";
const Buttons = () => (
<>
<button class={styles.btn1}>btn1</button>
<button class={styles.btn2}>btn2</button>
<button class={styles.btn3}>btn3</button>
</>
);
export default Buttons;
By the way, it is not necessary to use the word styles for the name of the imported object with styles, you can name it as you like.
In the next lesson we will complete our application.
Following the theory in this tutorial, generate a inputs React application.
Use the CSS modules approach shown in the tutorial. In src of your inputs app, create a Inputs.js file for the Inputs React component, which will contain three inputs. Write a couple of styles in Inputs.modules.css for the inputs. Import this file into Inputs.js and apply the styles.