The article is a short how to use CSS Modules in your create-react-app application . It shows you how to setup CSS Modules, but also how to use them in your components.
After you have setup your application with create-react-app (e.g. npx create-react-app my-app ), you donât need to install anything else to make CSS modules work. They come out of the box, but you have to give your CSS files the âmoduleâ prefix prior the extension: .module.css
Letâs try out how CSS Modules in React work. Letâs say our App component already uses a Navigation component to display links the following way:
Next, create the Navigation component in a src/Navigation.js file. As you can see, it takes a list of links as props and renders its content in a list of anchor tags.
Now, letâs say the following src/Navigation.module.css file has all the styles for the Navigation component. Structuring styling in a CSS modules could look the following way:
Now, import all styles as default by using an import statement in your src/Navigation.js file. The imported styles is an object where all the defined CSS styles can get extracted:
In case of the navigation style, you can retrieve it with styles.navigation too. However, for the other styles with dashes you need to retrieve them with strings from the object.
Once you start your application, everything should work as expected. You can find the final application in this GitHub repository . CSS modules are only one way of styling your applications. There are plenty of other ways to do it. In React, two other common ways of styling applications are styled-components and Sass .