Home > Software design >  Benefits of using CSS modules with React/Vue
Benefits of using CSS modules with React/Vue

Time:09-03

I would like to understand the benefits of using CSS Modules with React/Vue.

Currently in my company developers use the following in development:

return (
    <div className={styles.User}>
        <div className={styles.name}>...</div>
    </div>
)

While using a CSS module file, something like:

.User {
    background-color: var(--bg-color, red);

    .name { color: white; }
}

What should an HTML output such as:

<div >
    <div >...</div>
</div>

Which is a bit confusing for me, as this "encodes" all the class names and creates a great deal of difficulty if I need to do a parent-level modification. Eg.:

<div >
    <User name="David" />
</div>

So:

.SomeParent {
    > .User {
        --bg-color: blue; // Will not words, because .User is not .User, in fact.
    }
}

In personal projects, I prefer to name the primary element of the template by defining it as a "major class", the main. Eg.:

return (
    <div className="User">
        <div className="name">...</div>
    </div>
)

And a regular CSS/SCSS:

.User {
    background-color: var(--bg-color, red);

    > .name { color: white; }
}

So a parent element's code can affect a child element under expected and controlled conditions.

My question here is: what are the benefits of using the model that my company uses that I am not able to see? Am I missing something using a more "moderate/primitive" model?

Another possibility is: can I modify the style of child elements through the parent element, even with the name of the classes being encoded this way?

CodePudding user response:

SCSS module styles are applied by very unique classes thanks to the hash, and therefore have no real risk of unintended style collisions. This allows you to use short, meaningful class names without having to think of any global styles you might be colliding with. You can confidently style without fear of breaking things elsewhere in your application.

You could, in theory, add generic class names which are not applied via your scss modules to give your parent component a class name with which to work.

CodePudding user response:

CSS modules generate custom classnames for each style and therefore prevent the problem you are facing in your solution. Because each css module style has its own classname you cannot accidentially change a child components style.

CodePudding user response:

Personally I think the React components should be as modular and generic as possible. I think the way to go is such that types are exported from one component. Styles should be inline or at the bottom at a styles object.

  • Related