cover-img

CSS Modules in React

19 January, 2023

0

0

0

Introduction

While writing inline styles is okay for small apps, it does not scale well when we move to bigger applications that need to share styles. One of the solution to this scalability problem is CSS modules.

When we use CSS modules to style a React app, we create a separate CSS file and we import it as a module into the React file. There is also no issue of clashing styles in this methodology because each module file is independent.

Example of CSS module in React

Here is an example of using CSS modules in a React component:
First, create a CSS file for the component:

/* MyButton.module.css */
.button {
background-color: blue;
color: white;
font-size: 16px;
padding: 10px 20px;
}

Then, import the CSS file into the component and use the class names from the CSS module:

import React from 'react';
import styles from './MyButton.module.css';

function MyButton() {
return (
<button className={styles.button}>Click me!</button>
);
}

In this example, the CSS module is imported as a JavaScript object where the keys are the class names from the CSS file and the values are the generated class names. These generated class names are unique, so they won't conflict with class names from other CSS modules or from global styles.

Applying styles selectively

You can also use the class names from the CSS module in JavaScript expressions:

import React from 'react';
import styles from './MyButton.module.css';

function MyButton(props) {
const className = props.large ? styles.largeButton : styles.button;
return (
<button className={className}>Click me!</button>
);
}

In this example, the class name of the button is determined by the large prop. If large is true, the largeButton class will be applied, otherwise the button class will be applied.

Conclusion

CSS modules are a great way to style individual components in a way that is modular and scalable. They also make it easy to avoid class name collisions, because the class names are locally scoped to the component.

References

https://create-react-app.dev/docs/adding-a-css-modules-stylesheet/
https://medium.com/@ralph1786/using-css-modules-in-react-app-c2079eadbb87


0

0

0

ShowwcaseHQ
Showwcase is where developers hang out and find new opportunities together as a community

More Articles

Showwcase is a professional tech network with over 0 users from over 150 countries. We assist tech professionals in showcasing their unique skills through dedicated profiles and connect them with top global companies for career opportunities.

© Copyright 2024. Showcase Creators Inc. All rights reserved.