Using CSS Modules
Last updated
Last updated
Let's see how we do style things at Shopify with CSS Modules and classnames
. There are many other way of doing it, but that's what we chose to go with.
CSS Modules docs
css-loader
Github repo
classnames
Github repo
The main concept behind CSS modules is fairly simple: scoped CSS. If you worked with CSS in the past you know that it is really easy to have name collision. That resolves in using certain conventions like BEM to try to prevent name collision but it is still not bullet proof.
When using CSS Modules with React, all the CSS you write will be scoped to your component. In reality, what happens is that all the class names you use are hashed to make them unique at compilation time.
Everything happens at compilation or load time thanks to webpack and the plugin. I won't go into webpack details here, but css-loader
is just a CSS loader that is going to apply the principles of CSS Modules.
What happens in practice, is that instead of using your className
s as strings, you use a JavaScript object.
Let's see a simple example to illustrate how it works:
Note that the file we import is an SCSS file, so you still get all the power of SCSS!
It is as simple as that. And depending on the configuration of css-loader
the HTML output of this component will be something like:
You can also configure css-loader
to just have prefixes or suffixes to your existing classnames.
Because all the CSS is now scoped, we don't need to use BEM anymore. Therefore the following style of writing:
classNames
Now one question remains: how do you add multiple class names? Will I have to do things like:
Let's be honest, this is not really readable. And that's when the classNames
utility comes in play. It's a simple utility for conditionally joining classNames together.
Let's see a real world example:
Isn't this prettier?
There are plenty other way of styling in React, here are some well known and used libraries:
Styled Components
Glamorous
Glamor
Emotion
Styled-jsx