In the "main" component, I have implemented the render
method as shown below:
import ComponentA from './component-a.js';
import ComponentB from './component-b.js';
const App = React.createClass({
render: function() {
return (
<div>
<ComponentA/>
<ComponentB/>
</div>
);
}
});
The ComponentA
requires a separate css
file. Therefore, in the component-a.js
, I have included the following code:
require ('./component-a.css');
const ComponentA = React.createClass({
render: function() {
return (
<div>component a</div>
);
}
});
On the other hand, ComponentB
does not require any additional CSS file. For this component in the component-b.js
file, I only have the following code:
const ComponentB = React.createClass({
render: function() {
return (
<div>component b</div>
);
}
});
The specific css
style required by ComponentA
is defined as follows:
div {
width: 100px;
height: 30px;
border: 1px solid red;
}
Interestingly, even though only ComponentA
requires the additional css
file, it affects all div
elements on the page. This includes the div
of
ComponentB</code, despite not needing the style, and even the container <code>div
for both ComponentA
and ComponentB
, along with another dynamically added div
:
Why do
css
files seem to have a global effect rather than being limited to the specific component that requires them? What are the semantics behind requiring acss
file for a certain component?Is there any way to confine the effects of CSS files to only the relevant React component, aside from using inline styles or embedding everything within JS code? Using unique class names may not guarantee isolation when components are used together.