DEV Community

Chirag Jain
Chirag Jain

Posted on • Edited on

React Day Berlin 2018 - The Lonely and Dark Road to Styling in React -- Sara Vieira

This is my second post in the talk notes series. You can check out the first one here.

CSS is hard

Link tags

Blocks rendering, only ship the CSS you need i.e. critical CSS

BEM (Block Element Modifier)

.block__element—modifier

Pros

  • Easy to setup
  • Framework/Library agnostic
  • Fixes some specificity issue
  • Rigid Structure

Cons

  • Naming is hard
  • Need to memorise the rules and strictly follow them

Preprocessors

Pros

  • Nesting
  • Variables
  • SSR just works

Cons

  • Over Nesting
  • More dependencies
  • Makes it hard to author library → to modify, you need to run the preprocessor
  • Not optimised for a component based workflow
  • No dynamic styles based on runtime values

CSS Modules

Write normal CSS with classes and use them inside your components. In the end these will be replaced by random class names.

Use it via PostCss (Babel for CSS)

Pros

  • Can use all new CSS features
  • Autoprefixes CSS
  • SSR just works
  • More component based and maintainable

Cons

  • Unreadable class names
  • More dependencies
  • Needs to be paired with a pre-processor for variable support
  • Global class names can be abused

CSS-in-JS (Styled Components)

Just react components. No SSR support out of the box which can be mitigated by using Razzle (It will extract all the styles and give you style tags to insert into the HTML)

Pros

  • Dynamic styles (based on state and prop of the component)
  • Theming is super easy using the ThemeProvider component, It will pass the theme as a prop to the child component.
  • Can still use the cascade but the whole point is that the styles for your component are only for that component.
  • No more specificity problems.
  • Autoprefixes everything
  • No need to worry about naming things

Cons

  • Needs to change the way you think about CSS
  • Another thing to learn across the team
  • The library you are using might only support object based CSS
  • SSR is hard to implement yourself

There is nor Right / Wrong answer. Context / use-case matters when choosing a solution. For example: For prototyping you might want to use tachyons while if you need scalability you would probably go for something different or make something over it to avoid repeating classnames.

Link to the original Talk

If you liked this do check out other posts in the series :)

Top comments (0)