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.
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.
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 👇