-
|
Hey everyone! I had to manually configure CSS Modules in my project even after using create-react-app. Is it always that we have to manually configure or did I do something wrong when I created my project. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
|
Hi @unnatik, CSS module is turned on for files ending with .module.css. |
Beta Was this translation helpful? Give feedback.
-
CSS Modules in Create React App - Complete GuideCSS Modules are built-in and zero-config in CRA! No extra setup needed. Basic SetupJust rename file to /* Button.module.css */
.primary {
background: blue;
padding: 10px 20px;
border: none;
color: white;
border-radius: 4px;
}
.secondary {
background: gray;
color: black;
}
/* Button.jsx */
import styles from "./Button.module.css";
export function Button({ variant = "primary" }) {
const className = styles[variant];
return <button className={className}>Click me</button>;
}Key Benefits
Advanced PatternsCombining multiple classes: import styles from "./Button.module.css";
const buttonClass = [styles.base, styles.primary, isActive && styles.active]
.filter(Boolean)
.join(" ");
return <button className={buttonClass}>Text</button>;Or using classnames library (optional): npm install classnamesimport cn from "classnames";
import styles from "./Button.module.css";
return (
<button className={cn(styles.base, styles.primary, { [styles.active]: isActive })}>
Text
</button>
);CSS Modules + SCSSIf using SCSS (with /* Button.module.scss */
.primary {
background: blue;
padding: 10px 20px;
&:hover {
opacity: 0.9;
}
}When NOT to use CSS Modules
Migration from Regular CSS// Before (global CSS)
import "./Button.css";
<button className="primary">Click</button>
// After (CSS Modules)
import styles from "./Button.module.css";
<button className={styles.primary}>Click</button>That's it! CSS Modules give you component-scoped styling out of the box. Highly recommended for scalable CRA projects. See: https://create-react-app.dev/docs/adding-a-css-modules-stylesheet/ |
Beta Was this translation helpful? Give feedback.
Hi @unnatik, CSS module is turned on for files ending with .module.css.
It is also documented in CRA docs