Education
Software Development Executive - I
Last updated on Aug 20, 2024
Last updated on Aug 22, 2023
As a developer, I've always been fascinated by the power of CSS in enhancing the user interface of a web app. But when it comes to managing CSS in a large React project, things can get a bit messy. That's where React CSS Modules come into play.
CSS Modules are CSS files in which all class names and animation names are scoped locally by default. This means that the CSS code you write is tied to a specific component and won't interfere with the CSS code of other components. This is a significant advantage when working with a large React application where multiple stylesheets and CSS classes are in use.
Using CSS Modules in React brings several benefits. First, it helps to avoid global CSS classes that can lead to naming conflicts and unexpected side effects. With CSS Modules, I can use the same class name in multiple CSS modules without worrying about clashes.
Second, CSS Modules promote reusable CSS files. I can define a set of CSS classes in a CSS module and import styles from it in multiple React components. This is particularly useful when I want to share a common set of styles across multiple components.
Third, CSS Modules make it easier to manage CSS in a large React application. Instead of having a single, large CSS file, I can break down my CSS code into multiple CSS modules, each tied to a specific component. This makes my CSS code more modular and easier to maintain.
Before diving into the world of React CSS Modules, it's important to ensure that our development environment is properly set up.
To start using CSS Modules in a React project, we need to have a few things installed on our machine.
First, we need Node.js and npm (Node Package Manager). Node.js is a JavaScript runtime that allows us to run JavaScript code outside of a browser. npm is a package manager for Node.js and is used to install and manage packages that we use in our project.
Second, we need to have Create React App installed. Create React App is a command-line tool that allows us to create a new React application with a single command. It sets up the initial project structure and provides a set of scripts to build, test, and start the development server.
1 // To install Create React App, run the following command in your terminal 2 npx create-react-app my-app 3
Once we have the prerequisites installed, the next step is to install the necessary packages for using CSS Modules in our React application.
By default, Create React App comes with support for CSS Modules. This means that we don't need to install any additional packages or configure Webpack to start using CSS Modules. All we need to do is to create a CSS file with the extension '.module.css' and import styles from it in our React component.
1 // App.js 2 import React from 'react'; 3 import styles from './App.module.css'; 4 5 function App() { 6 return ( 7 <div className={styles.app}> 8 <h1 className={styles.title}>Hello, world!</h1> 9 </div> 10 ); 11 } 12 13 export default App; 14
In the above example, I import styles from 'App.module.css' in my App component. The styles object contains the CSS classes defined in the CSS module, which I can use in my component.
With the environment set up, we're now ready to dive deeper into React CSS Modules and explore their features and benefits.
Now that our environment is set up, let's create a new React application and integrate CSS Modules into it.
Once, you have created an React app, navigate to the project folder:
1 cd my-app 2
Now, start the development server and open the application in a web browser:
1 npm start 2
With the React application up and running, the next step is to integrate CSS Modules.
First, create a new CSS file with the extension .module.css in the src folder. For example, create a file named App.module.css. This file will contain the CSS classes for the App component.
1 // App.module.css 2 .app { 3 text-align: center; 4 } 5 6 .title { 7 color: blue; 8 } 9
Next, import styles from this CSS module in the App component:
1 // App.js 2 import React from 'react'; 3 import styles from './App.module.css'; 4 5 function App() { 6 return ( 7 <div className={styles.app}> 8 <h1 className={styles.title}>Hello, world!</h1> 9 </div> 10 ); 11 } 12 13 export default App; 14
In the above example, I import styles from App.module.css and use the CSS classes in my App component. The CSS classes are scoped locally to the App component, which means they won't interfere with the CSS classes of other components.
Before we dive deeper into using CSS Modules, it's essential to understand some of the basic concepts that underpin them.
One of the key features of CSS Modules is that they scope CSS classes locally by default. This means that the CSS classes defined in a CSS module are tied to a specific component and won't interfere with the CSS classes of other components.
For example, let's say I have a CSS module named Button.module.css with a class .button:
1 // Button.module.css 2 .button { 3 background-color: blue; 4 color: white; 5 } 6
I can use this .button class in my Button component without worrying about it clashing with a .button class in another component or a global CSS file.
1 // Button.js 2 import React from 'react'; 3 import styles from './Button.module.css'; 4 5 const Button = () => { 6 return ( 7 <button className={styles.button}>Click me</button> 8 ); 9 } 10 11 export default Button; 12
While CSS Modules scope CSS classes locally by default, they also support global scoping. This is useful when you want to define CSS classes that can be used across multiple components. To define a global CSS class, you use the :global keyword:
1 // App.module.css 2 :global .text-center { 3 text-align: center; 4 } 5
In the above example, .text-center is a global CSS class that can be used in any component.
Another powerful feature of CSS Modules is class composition. This allows you to create a new CSS class by combining other classes.
For example, let's say I have two CSS classes, .button and .large, in my CSS module:
1 // Button.module.css 2 .button { 3 background-color: blue; 4 color: white; 5 } 6 7 .large { 8 padding: 20px; 9 } 10
I can create a new CSS class, .largeButton, by composing the .button and .large classes:
1 // Button.module.css 2 .button { 3 background-color: blue; 4 color: white; 5 } 6 7 .large { 8 padding: 20px; 9 } 10 11 .largeButton { 12 composes: button large; 13 } 14
In my Button component, I can now use the .largeButton class, which applies the styles of both the .button and .large classes:
1 // Button.js 2 import React from 'react'; 3 import styles from './Button.module.css'; 4 5 const Button = () => { 6 return ( 7 <button className={styles.largeButton}>Click me</button> 8 ); 9 } 10 11 export default Button; 12
Understanding how to work with class names is crucial when using CSS Modules in a React project. Let's explore some of the best practices and techniques for managing class names with CSS Modules.
When working with CSS Modules, it's important to follow a consistent naming convention for your CSS classes. This makes your code easier to read and maintain and helps to avoid naming conflicts.
One popular naming convention is to use 'camelCase' for class names. This means that the first letter of each word (except for the first word) is capitalized. For example, 'myButton', 'mainContainer', 'headerTitle', etc.
Another approach is to use 'kebab-case', where words are separated by hyphens. For example, 'my-button', 'main-container', 'header-title', etc.
Regardless of the naming convention you choose, the key is to be consistent. This makes it easier for you and other developers to understand and work with your CSS code.
When using CSS Modules in a React component, you import styles from a CSS module as a JavaScript object. This styles object contains the CSS classes defined in the CSS module.
To use a CSS class in your component, you reference it as a property of the styles object. For example, if you have a CSS class named 'button' in your CSS module, you can use it in your component like this:
1 // Button.js 2 import React from 'react'; 3 import styles from './Button.module.css'; 4 5 const Button = () => { 6 return ( 7 <button className={styles.button}>Click me</button> 8 ); 9 } 10 11 export default Button; 12
In the above example, styles.button refers to the 'button' class in the CSS module.
If you want to apply multiple classes to an element, you can use the template literal syntax:
1 // Button.js 2 import React from 'react'; 3 import styles from './Button.module.css'; 4 5 const Button = () => { 6 return ( 7 <button className={`${styles.button} ${styles.large}`}>Click me</button> 8 ); 9 } 10 11 export default Button; 12
In the above example, the button element has two classes: 'button' and 'large'. The template literal syntax allows you to combine multiple classes into a single string.
Theming is a common requirement in many applications. It involves changing the look and feel of an application based on a set of predefined styles.
CSS Modules can be used to implement theming in a React application. One approach is to define a set of CSS classes for each theme in separate CSS modules, and then dynamically import the appropriate CSS module based on the current theme.
For example, let's say I have two themes, light and dark. I can create two CSS modules, LightTheme.module.css and DarkTheme.module.css, and define the styles for each theme:
1 // LightTheme.module.css 2 .body { 3 background-color: white; 4 color: black; 5 } 6 7 // DarkTheme.module.css 8 .body { 9 background-color: black; 10 color: white; 11 } 12
In my App component, I can then dynamically import the appropriate CSS module based on the current theme:
1 // App.js 2 import React from 'react'; 3 import lightStyles from './LightTheme.module.css'; 4 import darkStyles from './DarkTheme.module.css'; 5 6 const App = ({ theme }) => { 7 const styles = theme === 'light' ? lightStyles : darkStyles; 8 9 return ( 10 <div className={styles.body}> 11 Hello, world! 12 </div> 13 ); 14 } 15 16 export default App; 17
In the above example, the 'styles' object contains the CSS classes for the current theme. The 'body' class changes the background color and text color of the 'div' element based on the theme.
By using CSS Modules for theming, you can create dynamic and flexible themes that can be easily switched at runtime.
In conclusion, CSS Modules offer a powerful and flexible way to manage CSS in a large React application. They provide local scoping of CSS classes, promote reusability, and help avoid naming conflicts. Moreover, they support class composition and global scoping, enabling you to create complex styles with ease. With the ability to integrate theming, CSS Modules become even more versatile. By following best practices and understanding the underlying concepts, you can leverage CSS Modules to create clean, modular, and maintainable CSS code in your React projects. Whether you're a beginner or an experienced developer, mastering CSS Modules can significantly enhance your React development skills.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.