Tom Hanson
Tom Hanson

Reputation: 663

Styling in React

Having developed a few React-Native apps, I usually place all Stylesheet objects in a single Theme.js file that all components can require. I have found this really helpful and easier than each component having complicated Stylesheet variables.

In React, would a similar approach be recommended? Or am I able to use a conventional approach with a CSS file? There doesn't seem to be a definitive 'good' way of doing this.

Upvotes: 0

Views: 107

Answers (1)

purii
purii

Reputation: 6424

There can't be neither a correct nor a incorrect answer. It is a matter of personal preferences, based on pros and cons of some approaches.

Below are some approaches beside "complicated Stylesheet variables".

CSS-Modules

One possible solution might be the usage of CSS-Modules. By using CSS-Modules, you could enjoy the pros of real local scoping, which fits very well with the module-based model of react components. By that you can define dependencies and keep the style and markup together.

The Github-repo of CSS-Modules lists some points, which summarize possible pros of this technique:

modular and reusable CSS!

  • No more conflicts.
  • Explicit dependencies.
  • No global scope.

Classic CSS

It is also possible to use common CSS. Either with a preprocessor or not. With the usage of a naming convention, like BEM suggests, it is possible to imitiate local scoping with namespaces. (.cardmodule__)

This looks like a good approach to support a migration of an existing codebase to react. But it has its downsides with defining dependencies.


I'm sure, that there are much more arguments. Maybe some could be added to the list bit by bit.

Upvotes: 1

Related Questions