React with BEM

react-with-bem implements the BEM methodology for React.
Installation
Use your favourite manager to install the package:
yarn add react-with-bem
npm install react-with-bem --save
Usage
import React from "react";
import { BEM } from "react-with-bem";
import styles from "./App.module.scss";
export function App() {
return (
<BEM styles={styles}>
{
// set BEM block by using $block
// output: <main class="app">
}
<main $block="app">
{
// set a BEM element by using $element
// output: <div class="app__container">
}
<div $element="container">
{
// set BEM modifier by using $modifier (multiple modifiers are possible)
// output:
// <div class="app__container__hello> when emphasized === false
// <div class="app__container__hello app__container__hello--emphasized"> when emphasized === true
}
<div
$element="hello"
$modifier={{
emphasized: true,
}}
>
Hello World!
</div>
</div>
</main>
</BEM>
);
}
.app {
background-color: red;
color: white;
&__container {
max-width: fit-content;
margin: 0 auto;
&__hello {
font-size: 2rem;
&--emphasized {
font-weight: bold;
}
}
}
}
Please note:
- The use of CSS modules is optional. If you do not want to use CSS modules, leave out the
styles parameter of the <BEM> component.
- If you set the class name map via the
styles parameter of the <BEM> component, it will be used to map the BEM class names to the CSS module class names generated by your compiler framework.
- Good to know: BEM class names will be filtered out if they are missing in the provided class name map. It can happen if the Saas compiler filters out empty CSS classes. It is not a problem, but it might confuse you if you inspect the generated class names in the DOM inspector.
ESLint
Please add the following rule to your ESLint configuration to suppress errors related to the $block, $element, and $modifier attributes.
{
"rules": {
"react/no-unknown-property": [
2,
{ "ignore": ["$block", "$element", "$modifier"] }
]
}
}
Example
You can find a complete example here.