Why Is Css Imported Into The Global Scope In React?
Solution 1:
This is by definition of how CSS works.
CSS applies to the whole DOM - that's the nature of CSS. Once you've imported it somewhere in your code, it applies to the entire page if it matches the classes because default behaviour is to import into global space. Importing CSS simply includes that CSS in your output css file (or inline in your JS file if configured as such).
The only way around this is to use unique selectors or use local scopes, but both these only apply to code you write, not distributed files.
Local Scope Modules
Local scopes allow you to apply a unique selector scope at compile time through a framework such as webpack. In webpack, the appropriate tool (or loader in this case) is css-loader.
Unique Selectors
If you want to do it manually in your code, you'll need to wrap your elements in a common class, and only style those. This cannot be done easily for 3rd party css/code. For example:
<div class="componentXWrapper">
<button type="button" className="pt-button pt-icon-add" onClick={() => this.props.onClick()}>Blueprint button</button>
</div>
And with CSS target it with the following:
.componentXWrapper .pt-button {
//styles go here
}
.componentXWrapper .pt-button.pt-icon-add{
//styles go here
}
Though at this point I'd use SASS for simplicity
.componentXWrapper {
.pt-button
{
//styles go here
&.pt-icon-add{
//styles go here
}
}
}
Because it is a 3rd party library, you may not have control over this and they have clearly not used this pattern (that is, they do not use a wrapper, so classes are styled across the page instead of a localized section). In this case I would either opt to not use the third party CSS if its not working as expected, or just use the classes where needed if they are unique.
Post a Comment for "Why Is Css Imported Into The Global Scope In React?"