BEM stands for Block, Element, Modifier and is a methodology used to create reusable components in CSS by clearly defining and separating the roles of different class names.
Overview of BEM Components
- Block: The outermost parent component that acts as a standalone entity. For example,
.button
. - Element: A part of the block that has no standalone meaning and is semantically tied to its block. For example,
.button__text
. - Modifier: A flag on a block or element that changes its appearance or behavior. For example,
.button--large
.
BEM Example: Stick-Man (CSS)
BEM organizes CSS by using a structured class naming convention that enhances readability and maintainability. Here is an example using a simple stick-man illustration:
- Block:
.stick-man
- Represents the whole stick-man. - Elements:
.stick-man__head
- The head of the stick-man..stick-man__arms
- The arms..stick-man__feet
- The feet.
- Modifiers:
.stick-man--blue
- A blue version of the stick-man..stick-man__head--small
- A small head variation.
<div class="stick-man stick-man--blue">
<div class="stick-man__head stick-man__head--small"></div>
<div class="stick-man__arms"></div>
<div class="stick-man__feet"></div>
</div>
BEM Example: Button (CSS)
Suppose you are creating a user interface with a button that has different sizes and colors. Using BEM, the structure is defined as follows:
- Block:
.button
- The base class for all buttons. - Modifiers:
.button--large
- Modifies the button to be larger..button--success
- Modifies the button's color to indicate success (green).
- Element:
.button__text
- Targets the text within the button.
<button class="button button--large button--success">
<span class="button__text">Submit</span>
</button>
React Example: Product List
Implementing BEM in React with a ProductList
as the block and ProductListItem
as elements within that block.
This component serves as a container for product items.
// ProductList.jsx
import React from 'react';
import ProductListItem from './ProductListItem';
const products = [
{ id: 1, name: 'Apple', price: '$1' },
{ id: 2, name: 'Banana', price: '$2' },
{ id: 3, name: 'Cherry', price: '$3' },
];
function ProductList() {
return (
<div className="product-list">
{products.map(product => (
<ProductListItem key={product.id} product={product} />
))}
</div>
);
}
export default ProductList;
Each item in the product list is an element of the ProductList
block.
// ProductListItem.jsx
import React from 'react';
function ProductListItem({ product }) {
return (
<div className="product-list__item">
<h2 className="product-list__item-name">{product.name}</h2>
<p className="product-list__item-price">{product.price}</p>
</div>
);
}
export default ProductListItem;
Explanation:
- Block:
.product-list
- Represents the entire list of products. - Element:
.product-list__item
,.product-list__item-name
, and.product-list__item-price
- These elements are part of the ProductList and help in organizing components in a modular and reusable way.