Skip to main content

Command Palette

Search for a command to run...

The Digest Guide to React Styling

Updated
2 min read
The Digest Guide to React Styling
T

I have been around since the 90's (that's 1990) and even before as a geek girl. I have done development, product management, consulting, and system analysis, but my ultimate passion is system architecture and good coding practices. Today I work as an architect responsible for all the Frontend design, tooling, testing, and DevOps processes. I love Javascript and its ecosystem and will happily share this knowledge with fellow developers. Also, I am a Playwright Ambassador.


title: The Digest Guide to React Styling published: true description: Notes from understanding React Styling tags: React,CSS,CSS-in-js,css-modules

cover_image: https://thepracticaldev.s3.amazonaws.com/i/rbgzk6dc1bdody83ngqt.png

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.

More from this blog

Tally's Blog

24 posts

The Digest Guide to React Styling