How to style components in React with CSS modules?

  1. Install CSS modules: Start by installing CSS modules package using npm or yarn in your React project. You can do this by running the following command in your terminal:
npm install --save-dev css-loader style-loader
  1. Create CSS file: Next, create a CSS file for your component and name it with a .module.css extension (e.g., Component.module.css).

  2. Define styles: Use standard CSS syntax to define the styles for your component in the CSS file. You can use class names to style different elements within your component.

  3. Import CSS module: In your component file, import the CSS module using the following syntax:

import styles from './Component.module.css';
  1. Apply styles: You can apply the styles to your component elements by using the class names defined in the CSS module. For example:
<div className={styles.container}> <h1 className={styles.title}>Hello World</h1> </div>
  1. Use dynamic class names: You can also use dynamic class names in React components by concatenating the class names with variables or props. For example:
const isPrimary = true; <div className={isPrimary ? styles.primary : styles.secondary}>Hello World</div>
  1. Compile and run: Finally, compile your React project using webpack or another bundler to apply the styles from the CSS modules. Run your React project and see the styled components in action.

By following these steps, you can easily style your React components using CSS modules, which provide scoped styles and prevent style conflicts in your application.