DEV Community

Yale Araujo
Yale Araujo

Posted on

Using CSS Modules how to style components according to their props

Certainly you as a Frontend Developer will need style some component according to the props that your component assume.

Often it's a button which could assume different possibles: success (green), error (red), default (default color), but you can apply for all types of components.

Using CSS Modules React Components are styled with classes, in React classNames:

Image description

And the CSS archive:

Image description

But what to do when the component can assume different background-colors?

Lets improve our code using literals string!

Image description

Above the component Button could assume: primary, secondary, success and danger. And according the color props value, the background needs change!

Image description

Now we have a base className which defines the width and the height of the button, and also a second className to set the background color.

This is possible because styles it's a object which get our classes like your properties. And we can access their values using the traditional syntax "styles.button" or "styles[color]".

I hope help you writing this small text!

Yale Araújo
Frontend Developer

Top comments (0)