简体   繁体   中英

Why to use separate CSS files for components in React.js

I am new to Web Development and currently learning React.js. I learned about how to create Components in React and giving styles to them.

Is it like that if I create separate CSS files for React Components, the app will load faster because the browser has to load small sized CSS files instead of single big file?

I want to ask about how React loads the CSS files in the browser and whether I should use separate CSS files for React Components.

Yes, you want separate files. No, the reason why you do it isn't for performance (although it certainly can have an impact on performance).

You're missing that components should be re-usable .

If I create an AwesomeWidget component and I want to drop it straight into another project I'm working on then I should be able to do that with as little friction as possible. And you can't do that if its styles are mixed in with application-specific stuff. Your components should be, insofar as is possible, independent of what's around them.

Keep the component-specific files separate and let Webpack do the work of wiring it all up for you. If you find yourself reusing a component enough then move it into its own repo (don't forget you can npm install from a git url if you don't want to publish it to the public package registry).

yes, it is preferred to make every component with its stylesheet and also use CSS modules file to make it scoped. also separating your CSS file is for readability only and for you as a developer it has nothing to do with loading faster because your bundler will compress all CSS files into a single one to make it loaded faster. I hope My answer is clear and enough for your question.

In your project folder you will see index.css or app.css, write your style there . Example

.divcontainer{ }

So in your class now whenever you want to use the css style Use class=“divcontainer” in the tag not className=“divcontainer ”

You can import the CSS directly into the component.

Example: import './style.css'

Or you can use the styled-component library to work with CSS I recommend it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM