styled-jsx lets developers write CSS-in-JS in a more declarative fashion compared to other CSS-in-JS solutions. In my opinion, it leads to code that's easier to understand.
Before I tell you why I prefer styled-jsx, let's learn about some programming concepts—It'll all make sense later, trust me!
Next: What does it mean to write 'more declarative' code?
There are two styles of expressing data. The most common way is to simply write it out as a data structure. We can call this a declarative style of writing, where we try to express logic without providing any instructions.
There are cases when this style may not be flexible enough, so some systems take an imperative approach. In contrast to the declarative style, it's a piece of code with instructions that runs procedurally. Here's an example of a Ruby gem specification, which defines a Ruby package's metadata.
Next: What's the difference?
Ruby's gem specification style is imperative because we're issuing instructions that are to be ran sequentially. It can keep variables, call functions, and do all the things you can do in a Ruby program. Think of the Ruby gemspec as a program talking to the system:
Next: What makes imperative-style different?
Imperative style gives you the power to write expressions that you can't easily do with a declarative-style conventions. For instance, here's an example gem specification where the list of files are gathered via a system command (
CSS is beautifully declarative. To write CSS is to write a list of rules, not a set of instructions. For instance, we would say buttons are supposed to be blue, rather than turn all buttons to blue.
However, how would you start making red
danger buttons? With styled-components, you'll have to provide a function which returns a CSS fragment depending on how you would interpret
How would you style a danger button differently in styled-jsx? Just use CSS classes as you normally would. Simple!
Since writing this article, I've decided that I like the simpler approach of just using CSS modules. The reasons for that is the same as what's in this article: it's as declarative as you can get, and it's compatibility with existing tools is so far unbeatable.