How does parent component's imported css file is used inside child components?

  1. App.jsx has import './App.css';

  2. App.jsx has got 2 child components

  3. Now these 2 components uses classes from App.css without explicit import statement ?

How is this possible ?

Your styles are not encapsulated in the component in React, you should use more specific class names if you want styles to apply only to one component, i.e. using BEM as suggested in the link above

Thanks for update, but my question was different.

I figured out that child components will have access to parent component’s style sheet file without explicit import. I was not aware of this logic

Webpack (which is what I assume you’re using via create react app?) isn’t doing anything clever here apart from letting you use the line import "SomeCSSFile.css" in a JS file even though it’s not JS.

When the code is compiled, the build tool looks for every one of those import statements, uses them to store the paths to the CSS file, removes them from the end code, then joins all of the CSS files it’s found together into one.

You just end up with a single CSS file, it doesn’t mean you have a special set of CSS that only applies to the code in App.js.

The ability to write that import in the JS for the CSS files is just for convenience. The CSS is still CSS, it works the same and cascades. As @miketandy says, you still need to write the CSS with specific class names to target specific components.

There are ways to get encapsulated styles (CSS modules, which are supported out of the box with CRA, or CSS-in-JS libraries, of which there are many, or just by writing your CSS carefully, where you can use techniques like BEM)

Thanks, can you please refer to any blog or youtube video about CSS good practice. CSS is such flexible; I’m lost atm what’s the best way to use it ?

I mean, that’s quite a large subject, but at a basic level, just add classes to the things you want to style. FCC has a full CSS course so I can only really advise going through that – at a basic level CSS isn’t enormously complicated, but even if you use a tool in your React app that gives you encapsulated styles, you still need to understand it

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.