DEV Community

loading...
Cover image for BEM in React

BEM in React

jonmajorc profile image Jon Major Condon ・2 min read

I default to SCSS without modules for styling React applications. Therefore willingly my styles cascade. You're probably thinking, Eek! That means potential specificity wars ahead. Although there technically could be, each component uses a naming convention for class names.

Traditional BEM naming convention for class names is block__element--modifier.

  • A block is the element in your React component that wraps all other elements. There is only one block per component.
  • An Element is within the Block.
  • A Modifier represents behavior on an Element or Block.

Pretty simple right? Here is a start to a component.

const Counter = () => {
  return <div className="Counter">Start of an amazing counter component</div>
}

Notice: The class name is the name of the component with the same casing.

Let's extend that example so we can see more of BEM in action.

const Counter = () => {
  return (
    <div className="Counter">
      <button className="Counter__inc">Click me!</button>
      <span className="Counter__count">0</span>
      <button className="Counter__dec">Click me!</button>
    </div>
  )
}

Notice: The class name for elements are prefixed with the Block class name followed by a double underscore.

Let's add a modifier to this component!

const Counter = () => {
  return (
    <div className="Counter">
-      <button className="Counter__inc">Click me!</button>
+      <button className="Counter__inc Counter__inc--disabled" disabled>
        up
      </button>
      <span className="Counter__count">0</span>
-      <button className="Counter__dec">Click me!</button>
+      <button className="Counter__dec Counter__dec--disabled" disabled>
        down
      </button>
    </div>
  )
}

Notice: The original class name for an element is cloned, along with a double dash, followed by a modifier.

The buttons are now disabled. If you noticed, the buttons are missing click events anyways. For this demonstration, we don't really care to have a working example; we just want to see BEM. Theoretically, this application is looking good πŸ™ƒ We should have more confidence that styles are scoped to <Counter /> when it mounts!

The Post was growing too large. To keep it small and concise, and hopefully still digestible, I started with introducing BEM. I hope to move on to how I use BEM with 7-1 sass architecture and some other principles to create modular and maintainable style sheets! ...BEM is only part of the equation.


Hello! I'm Jon Major Condon. I am a Senior Software Farmer that tends to client codebases at Bendyworks. As a farmer of software, I focus on anything web, but my curiosity usually leads me down rabbit holes... "Jon Major just fell down another rabbit hole… Stay tuned for the next blog post! πŸ‘‹"

Discussion (0)

pic
Editor guide