When using CSS Modules, accessing the styles requires a slightly different approach. You should
import styles from 'Component.module.css';
and then define your styles by using the imported object like
styles.MyClass
. If you have hyphens in your class names, you'll need to use bracket notation like
styles["top-bar"]
Check out this working sandbox
//MyComponent.js
import styles from "./MyComponent.module.css";
export default function MyComponent() {
return (
<div id={styles["top-bar"]}>
<h2>My Component</h2>
<InnerComponent id="inner" />
</div>
);
}
function InnerComponent({ id }) {
return (
<div id={styles[id]}>
<h3>Inner Component</h3>
<p id={styles.para}>Styled Paragraph</p>
</div>
);
}
//MyComponent.module.css
#top-bar {
width: 90vw;
margin: 1rem auto;
padding: 1rem;
text-align: center;
background-color: LightPink;
}
#inner {
background-color: LightBlue;
text-align: left;
}
#para {
color: red;
}
Here's a brief example demonstrating the usage with IDs.
function MyComponent() {
return (
<div id="top-bar">
<h2>My Component</h2>
<InnerComponent id="inner" />
</div>
)
}
function InnerComponent({id}) {
return (
<div id={id}>
<h3>Inner Component</h3>
</div>
)
}
ReactDOM.render(<MyComponent />, document.getElementById('App'));
#top-bar {
width: 90vw;
margin: 1rem auto;
padding: 1rem;
text-align:center;
background-color: LightPink;
}
#inner {
background-color: LightBlue;
text-align: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="App"></div>