CSS Modules in 2 minutes

CSS modules are not my favorite, but they're pretty much the best option you have if you already have a bunch of existing CSS files, and you want to reuse them in your react project.

They work by letting you import a bunch of CSS files and turn them into JavaScript objects that you then pass into your class names prompt for your react component. Each file becomes a huge object where every class in your file becomes a key in that object. Those map to specific, very specialized class names, that get rendered into your HTML. It's probably best if I show you how it looks in code.

Let's try starting this bottom over here with CSS modules. We're gonna start by creating a new file. Bottom.module.css. Rounded borders with a border in button.js. Import styles from the file we just created, and to use those styles, we go into our button and add a class name. This class name should come from styles.button. We now have a rounded border button.

If you look at what's actually generated from this, it's got this really weird class name, but if we look up here, we'll see that the CSS should be getting loaded as a special blob. When you deploy full production, it gets loaded as a huge CSS file that has all these special classes that only apply to particular components.

If we want to move this button, these other button styles, a button has a margin of translating our CSS in JavaScript back to normal CSS, which is probably what you are used to. A green button has the same styles we used before, and also "composes: button". If we change class name to green button, it's basically how CSS modules work.

What's really cool is that you can see that this CSS modules stuff still composes very well with what our original style prop, where we are overriding a specific value, based on some state, and using CSS modules to style everything else. And that's exactly what we wanted. We have normal CSS files that look just like the files we're already used to. You can compose different things together, just like you normally would. And you can see that specific files only apply to specific components so you get proper componentization.

Know someone who wants to learn React and its whole ecosystem? Share 👇


Cheers,
~Swizec