Usage in JavaScript/React Component
To use the styles defined in the “button.module.css” file, you import the module in your JavaScript or React component. Here, the “styles.button” syntax ensures that the styles are locally scoped to the “Button” component, avoiding any unintended global style conflicts.
/* button.module.css */
.button {
background-color: #3498db;
color: #ffffff;
padding: 10px 15px;
border: none;
border-radius: 5px;
cursor: pointer;
}
.button:hover {
background-color: #217dbb;
}
// Button.js
import React from 'react';
import styles from './button.module.css';
const Button = () => {
return (
<button className={styles.button}>
Click me
</button>
);
};
export default Button;
//app.js
import './App.css';
import Button from './Button';
function App() {
return (
<div className="App">
<Button/>
</div>
);
}
export default App;
Output:
CSS Modules : Local Scope for styles in React
CSS Modules enable you to write styles in CSS files and then consume them as JavaScript objects, offering additional processing capabilities and enhancing safety. They have gained popularity due to their automatic generation of unique class and animation names, alleviating concerns about selector name collisions.
Table of Content
- What is CSS Modules?
- When to use CSS Modules?
- Concept of Local Scope for styles in CSS modules:
- Local Scope in CSS Modules:
- Usage in JavaScript/React Component
- Advantages of Local Scope
- Conclusion
Contact Us