BEM naming convention for organized CSS classes
In React applications, managing CSS classes can become challenging as your project grows in size and complexity. The BEM (Block Element Modifier) naming convention provides a structured approach to naming CSS classes, making it easier to organize and maintain your stylesheets. This lesson will introduce you to the BEM naming convention and show you how to use it to create organized CSS classes in your React components.
What is the BEM naming convention?β
BEM is a popular naming convention for CSS classes that stands for Block Element Modifier. It helps you create modular and maintainable stylesheets by defining a clear and consistent naming structure for your CSS classes. BEM divides your styles into three categories:
- Block: A standalone component that can be reused across your application.
- Element: A part of a block that has no meaning or use outside of the block.
- Modifier: A variation or state of a block or element.
By following the BEM naming convention, you can create self-explanatory and reusable CSS classes that are easy to understand and maintain. Here's an example of using BEM in a React component:
/* Block */
.button {
display: inline-block;
padding: 10px 20px;
background-color: #007bff;
color: #fff;
border: none;
border-radius: 5px;
}
/* Element */
.button__icon {
margin-right: 5px;
}
/* Modifier */
.button--disabled {
opacity: 0.5;
cursor: not-allowed;
}
In this example, we have defined a block .button
, an element .button__icon
, and a modifier .button--disabled
using the BEM naming convention. This structure helps you organize your styles and understand the relationship between different parts of your components.
How to use BEM in React componentsβ
To use the BEM naming convention in your React components, you can apply the BEM structure to your CSS classes and use them in your JSX elements. By following the BEM naming convention, you can create consistent and maintainable styles for your components. Here's an example of using BEM in a React component:
import React from "react";
function Button({ children, disabled }) {
return (
<button className={`button ${disabled ? "button--disabled" : ""}`}>
{children}
<span className="button__icon">