Nearby lessons
13 of 44🎨 ReactJS – CSS Modules
📌 What are CSS Modules?
What are CSS Modules in React?
CSS Modules let you write CSS that is locally scoped to a specific component. This means class names and styles are unique to that component, avoiding conflicts with other styles in your project.
Unlike normal CSS files which are globally scoped,
CSS Modules are locally scoped by default.
The browser transforms the class name into a unique identifier such as:
Filename_classname_hashcode.
📌 Key Points about CSS Modules
- CSS Modules are convenient for components placed in separate files.
- They prevent name conflicts by scoping styles locally.
- CSS stylesheets (external styles) are globally scoped.
- CSS Modules require
react-scripts@2.0.0or higher. - In the browser, CSS class names are converted into a unique format:
Filename_classname_hash.
⚙️ Using CSS Modules
Let’s see how to use CSS Modules in React with two components.
React Playground
import Stylesheet1 from './Stylesheet1.jsx'; import Stylesheet2 from './Stylesheet2.jsx'; export default function App(props) { return ( <> <Stylesheet1/> <Stylesheet2/> </> ); }
🧩 Using Multiple CSS Modules Together
You can also import multiple CSS Modules inside one component.
This way, you can combine different styles while keeping them scoped properly.
React Playground
import Stylesheet1 from './Stylesheet1.jsx'; import Stylesheet2 from './Stylesheet2.jsx'; export default function App(props) { return ( <> <Stylesheet1/> <Stylesheet2/> </> ); }
🧠 Test Your Knowledge
3 QuestionsProgress: 0 / 3
Keep Going!React - Bootstrap