A solution to scoped styling of components

Most modern web applications built with React.js or other libraries, consist of many components that have their own functionality and styles. Styling all these components can quickly turn into a disorganised situation if not done the right way, so how exactly should you style your components?
Fortunately, a methodology by the name of Block Element Modifier or BEM exists, to make it easier for you.

Summary

What are some common styling problems?

  • Styling out of component scope
  • Over-qualifying selectors and use of !important
  • Unclear what styles are exactly doing

How to solve these problems?

We are going to apply the BEM methodology to solve these problems, but first you need to understand what exactly BEM is. Shortly said, BEM is a naming convention for writing cleaner and more readable CSS classes using unique class names for each component (block).

Advantages of using BEM

  • Creating modular and independent blocks
  • Blocks are re-usable and thus reduce CSS
  • Block styles remain simple and are easy to understand
  • Developers spend less time styling components

BEM explained

The BEM naming convention for class names is as following.

block__element--modifier

A block represents the wrapping element of your component, there is only one per component.
An element is any element within your block.
A modifier is used to change appearance, behaviour or state.

I strongly encourage you to read through the naming conventions rules on the original BEM website.

Let's take a look at an example.
Example of BEM
View on Codepen

Generate class names using a library

You can use the BEM methodology in your project without installing any libraries, however, to efficiently generate the class names you can use a library like rebem-classname that does the job for you.

  1. Install the ‘rebem-classname’ package
    npm install rebem-classname

  2. Use stringify to generate BEM class names in your component:

import { stringify } from 'rebem-classname';

import './Component.style.css';

function Component() {
    const bem = stringify({ block: 'block', elem: 'elem', mods: { mod: true } });
    return <div className={bem}>I'm using BEM!</div>;
}

export default Component;

Render result:

<div class="block__elem block__elem_mod">I'm using BEM!</div>

Thank you for your read!

I hope you enjoyed reading my post and have learned something, feel free to give a like and comment below to give some feedback.

20