Question about styling React components best practice

Hi, just wondering what is the best practice for styling React components, is it better to style the components individually or style them in the root html page? Thank you.

Not a React expert—please take the following opinion with a grain of salt:

I don’t think there is a single “best” way to style things; it depends how large your project is, how often your components are reused in your project, whether or not you plan to make a library out of those components either for personal or public use, your setup… etc.

Assuming you are using create-react-app, importing a CSS into your component (for example import './index.css/') is functionally the same as importing one with <link href="path" rel="stylesheet">. Having said that the former, in my opinion, offers a better way to compartmentalise/organise component-specific styles.

The advantage of doing things either of the two ways mentioned above is that you are implementing styles with the CSS syntax (I personally enjoy writing CSS), and that you can take full advantage of every styling method, available to CSS (well, it is CSS). This works great for global styles. The down side is also that you are still limited by what CSS can and can’t do—styling things dynamically in cases that are not handled by CSS events is not easy (putting it lightly) depending on your use case.

Whichever of these two methods you use, do keep in mind that the styles are global, and that brings us to the next bit.

As you probably already know, a react component can accept a style prop that defines the component’s styles. I’m not entirely sure what is under the hood, but, whatever it is, it’s very similar to the style property of a regular DOM element and the output are inline styles that resemble what vanilla JavaScript styling would give you; I believe this is also often called inline-styling (but probably misleading since only the HTML output in the is similar/the same).

The advantage here is that you can style things dynamically with JavaScript and, in addition, the styles are not global and scoped to the component. The down side is that you’re not writing CSS and certain things can become very cumbersome, such as event-based transitions (for example, .classname:hover {}) or @keyframes animation.

If an extra dependency is okay for your project, you could also use styling libraries like styled-components, which is quite flexible in many ways, such as allowing you to style with an SCSS-like syntax and, as far as I know, generates unique CSS classes for components.

I hope that helps!

1 Like