Reputation: 6089
In React I have a Component and I want to import a css stylesheet
import styles from 'css-stylesheet.css'
or
import 'css-stylesheet.css'
in './MyComponent.jsx'
However I only want this css to apply to THIS COMPONENT ONLY! I dont want it to be global as it is now. I am using webpack. Is there a way to import css locally and only apply it to the file I imported it from? Seems like there should be a way but I cant even find a question about it.
Here is my webpack css loader code
module: {
rules: [{test: /(\.css)$/, loaders: ['style-loader', 'css-loader']}]
}
Upvotes: 0
Views: 1188
Reputation: 35553
You are using css-loader, it supports css-modules, to enable it you should pass an option
{
loader: "css-loader",
options: {
modules: true
}
}
That will return you an object whenever you're importing css, and that object will contain a map between your css selectors to uglified selector, in that way, the styles are unique to the component.
You can define the pattern of the uglified selector, by adding additional field to the options.
localIdentName:[name]__[local]___[hash:base64:5]
Upvotes: 1