Use CSS Modules with Create React App 2.0

Elijah Manor
InstructorElijah Manor
Share this video with your friends

Social Share Links

Send Tweet

create-react-app version 2.0 added a lot of new features. One of these features is to add CSS Module support. CSS Modules automatically scope class names and animation names local by default to get around the problem of global name clashes. You can learn more by looking at the CSS Modules repository.

Instructor: [00:01] First, let's create a new React app with npm init react-app in the name of our application. I'll call it CRA2-CSS-modules. Immediately, cd into the app after it's bootstrapped. Once everything is created, then open our VSCode with code period and start the React Dev Server with npm start.

[00:23] Next, create a folder named link and create a link.js file and a link.module.css file. Pray react-version2 recognizes this file convention .module.css to indicate CSS module support.

[00:38] Starting in our link.js file, import React from React, and import styles from the link.module.css file. Briefly switching to our link.module.css file, let's add some styles. Add a default class with color of 61dafp to match the blue in the app and give a padding of five pixels.

[01:02] Then, add a warning class that composes the previous default class and change the color to 282c34 to match the dark gray and give it a background color of yellow. Lastly, we'll make an error class that composes the styles from the warning class and give it a color of red.

[01:20] Let's switch back to the link JS file and export default, a new component that accepts props, and destructure from the props mode with an initial value of default children and gather the Rust in a Rust variable.

[01:35] Next, we'll return an anchor component providing class name that will fill out in a minute and spread the rest variable over the component. We'll pass children from the parent as its contents. Coming back to the class name, we could leverage the styles we imported from our CSS module.

[01:53] We could provide styles.default, or styles.warning, or styles.error. In our case, we'll use the mode that is passed in and dynamically pick the style. Switching to our app.js, we'll import link from link/link and replace the anchor component with the new link component.

[02:15] We could delete the class name as it's not used anymore. If we inspect our element in dev tools, we can see that there is a dynamically generated class name that's provided, link_default__2xemptyj.

[02:30] Provide the mode prop and give it a value of default. You notice that the result doesn't change, because default was the initial value to begin with. Let's try changing the value to warning. The UI will update in your c and dev tools that the class changes accordingly.

[02:47] Finally, switch the mode value of error. You notice the class and styles are updated again to what we expected.