33
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.
Fortunately, a methodology by the name of Block Element Modifier or BEM exists, to make it easier for you.
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).
The BEM naming convention for class names is as following.
block__element--modifier
A
An
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.
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.Install the ‘rebem-classname’ package
npm install rebem-classname
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>
I hope you enjoyed reading my post and have learned something, feel free to give a like and comment below to give some feedback.
33