Choosing the right method for styling components isn’t an absolute truth. It’s a relative choice that should serve your use case, it depends on your personal preferences and the specific complexity of your application.
In this article, we’ll show useful ways to style your React components. The choice is yours, and please feel free to add your own experience, insights, and suggestions.
3-CSS in JS
React lets you add CSS inline, written as attributes and passed to elements.
In React, inline styles are not specified as a string. Instead they are specified with an object whose key is the camelCased version of the style name, and whose value is the style’s value, usually a string.
You can pass the styling directly or create a variable that stores style properties and then pass it to the element. With inline styles, you also have the option to combine CSS syntax with JSX code.
Regular CSS is a common approach, arguably one step better than inline CSS.
The styles can be imported to any number of pages and elements unlike inline CSS, which is applied directly to the particular element.
Normal CSS has several advantages, such as native browser support (it requires no dependencies).
You can maintain any number of style sheets, and it can be easier to change or customize styles when needed.
There are several benefits to this approach. For example, the generated CSS is scoped by default, meaning that changes to the styles of a component won’t affect anything else outside that component.
react-jss is a library that implements the above-mentioned CSS-in-JS technique.
A CSS Module is a CSS file in which all class names are scoped locally by default.
CSS class names are scoped globally by default. This can lead to conflict, especially in large stylesheets, one style can override another. This is the problem CSS Modules solves. CSS classes are only available within the component where they are used.
Remember that the main purpose of CSS Modules is to make CSS classes locally scoped and avoid conflicts in naming.
All these ways of styling react components have pros and cons.
It all boils down to both your own personal preferences and the specific complexity of your application.