Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 844
Rohit Rawat Avatar asked Feb 29 '20 11:02

Rohit Rawat


People also ask

Should React components be in separate files?

React is all about re-using code, and it is recommended to split your components into separate files. To do that, create a new file with a .js file extension and put the code inside it: Note that the filename must start with an uppercase character.

Should I create a CSS file for each component?

yes, it is preferred to make every component with its stylesheet and also use CSS modules file to make it scoped.

What's the benefit of using a separate file to store your CSS?

Readability: It's definitely easier to just open the file that contains css rules instead of your huge HTML file looking for the culprit. So, it is easier to maintain your website.

Do we have to write CSS files to style React components?

Plain CSS. Instead of using inline styles, it's common to import a CSS stylesheet to style a component's elements. Writing CSS in a stylesheet is probably the most common and basic approach to styling a React application, but it shouldn't be dismissed so easily.


1 Answers

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).

like image 100
Jared Smith Avatar answered Sep 18 '22 13:09

Jared Smith