How I Style React Components

I don't like putting CSS in Javascript, so I avoid it whenever I can.

It isn't ideal to avoid it entirely: sometimes you need to calculate a value for some style rule, or test some condition in order to assign the right className to an element. This is easily done with Javascript, but impossible with static CSS alone.

But JS-based solutions aren't right for me, either. The reasons I don't like them are that they stack on more complexity in order get around a simple process we already know how to perfectly well.

It also adds a lot of verticality to your javascript file. CSS rules are usually narrow and tall, with even the simplest rule requiring three lines or so. This means you either do a lot of scrolling past CSS to get to your Javascript, or you make sure to separate the styled JS into its own file, and import it properly. You should do this last part anyway, but nobody does.

After making fairly extensive use of some popular JS solutions, I settled on a process where all CSS is scoped to the component it provides style rules for. The styles are kept in a separate file, so they don't pollute your component javascript.

I use Stylus as a CSS preprocessor, because I like the absolute minimalist syntax and the consistent grammar of its built-in functions, but there is absolutely no reason you couldn't use SASS, or LESS, or any other preprocessor that supports nesting. You may use no preprocessor at all.

You don't even need to nest your styles if you don't want to, but if you don't, you will need to repeat the component class name on every line by hand.

Assuming I am working on a React component called DetailCard, my method is simply:

  1. Create a DetailCard.js file
  2. Make sure the Component's root element has className='DetailCard'
  3. Create a DetailCard.styl file
  4. Make the outermost style .DetailCard, and then nest all other styles inside it, like this:
    background-color red
      font-size xx-large
      color white
      margin-top 2.4rem

.The key thing is that all styles are contained in, and scoped by, a classNamethat is tied uniquely to your component. This prevents the CSS from leaking into the global name space, at least in theory. If you have multiple components with the same name, that is a separate problem!

I'm of the opinion that trying to avoid global styles altogether is not worth the cost. It often leads to needlessly repeating the same styles over and over, because your strictly-scoped solution has kept you from reusing it. The C in CSS stands for Cascading, and you shouldn't be afraid of it.

Anyway, some CSS should be global, like reset or normalize, not to mention your site's typographical rules.