Search code examples
javascriptreactjssassclassnamebem

Issue with "M" in BEM with React CSS Module


I'm trying to incorporate BEM with my project. It was fine with the element part (block__element), but I'm keep getting an error when I try to name the modifiers (block__element--modifier). Below is my code including the error, the mixin I wrote for BEM, the SCSS snippet, and the setting in my IDE (webstorm). I tried all different things (not using mixin, etc.) but nothing seems to work. Please help!

React

Sass MixinerrorWS Setting


Solution

  • The way you using modifiers is incorrect at all.

    Modifiers are not sub-elements, they are modifiers for blocks and elements and can't be used without mother-eneities.

    Correct:

    • <div class="b">
    • <div class="b__e">
    • <div class="b b--m1 b--m2">
    • <div class="b__e b__e--m b__e--m2">

    Incorrect:

    • <div class="b--m1">
    • <div class="b__e--m">

    The reason why it works like this is the nature of modifiers — they are things very close to interfaces or mix-ins, they can't be used without blocks like interfaces can't be used without classes.

    Read more about modifiers here: https://en.bem.info/methodology/key-concepts/#modifier

    Another thing you should not repeat BEM-structure in your HTML-structure.

    So this is Incorrect:

    <div className={styles.card__content}>
        <div className={styles['card__content--icn']}>Icon</div>
        <div className={styles['card__content--sub']}>Test</div>
    </div>
    

    And this is Correct:

    <div className={styles.card__content}>
        <div className={styles.card__icon}>Icon</div>
        <div className={styles.card__sub}>Test</div>
    </div>
    

    See https://en.bem.info/methodology/faq/#can-i-create-elements-of-elements-block__elem1__elem2


    If you interesting in using BEM with React you should take a look at bem-react-core — tiny library that helps you generating BEM-classes, provides runtime, etc.: