DEV Community

loading...
Cover image for The Digest Guide to React Styling

The Digest Guide to React Styling

Tally Barak
Coding is a craft and art. 30 years of learning software tools and practices. Making the life of the development team simple, efficient, and fun.
・2 min read

Are you confused over the different styling approaches for components in React? So am I.
To avoid verbosity, I summed it up in 5 bullet points and 4 images, with some footnotes.
Use this article as a starting point for exploring deeper with a basic understanding of how each method works.

CSS in the DOM

Here is how you can add styles to a web page:

External stylesheet

<link rel="stylesheet" type="text/css" href="mystyle.css">

The styles are global and applied on the whole DOM

Embedded (internal) stylesheet:

<style>
   p {
        font-family: georgia, serif; 
        font-size: x-small;
    }
</style>

Also here, the styles are global and applied on the whole DOM

Inline styles

<h1 style="color:blue;">This is a Blue Heading</h1>

The style is local and impacts only the element

Scoped CSS - deprecated!

https://caniuse.com/#feat=style-scoped

Shadow DOM CSS

It is a style tag that only applied to the shadow DOM part where it is included.

CSS in React

Let's see how React styles are translated to the above (internal and external stylesheet and inline styles):
General note: Any .CSS file bellow can also be a CSS with pre-processor such as Less or Scss file.

Basic Styling

With styles

Alt Text

With classes
Alt Text

  • Styling is processed during build time.
  • Styles can be exported to an external stylesheet.
  • Dynamic styling can be achieved using changing inline styles or applying dynamic classes.

CSS Modules

Alt Text

  • Styles are created during build time (Webpack)
  • Styles can be exported to an external stylesheet.
  • In Create-React-App CSS modules are differentiated from regular CSS by adding the .module.css suffix to the files. Webpack configuration in CRA refers to this suffix.

CSS in JS

Alt Text

  • Styles are created during runtime.
  • Some libraries allow extracting static CSS parts to external CSS stylesheet (critical CSS).
  • In CSS in JS JS objects are playing the role of classes.

Discussion (1)

Collapse
daverubin profile image
DaveRubin

Simple and informative...
Thanks!