Code is read much more often than it is written
– Guido Van Rossum, Creator of Python.
It is of utmost importance that we make our code as readable and semantic as possible, so that the next person who comes and reads it is able to quickly understand what the intention was, what the logic is, and how to alter it to meet the new business requirements.
It is generally accepted that inline styles are not the best idea, because they make the code so much less readable.
Imagine if we were on a page that contained several such components. It would be very hard to make sense of it.
Now that really doesn’t look nice, does it?
Raw CSS / SASS
Of course, we could abstract our styles to an external stylesheet, but that is also not an ideal solution.
The problem with using raw CSS or SASS in your JSX is that if it is not namespaced with great manual care, another developer could easily overwrite your styles by accident without being aware of the cascading effects they’ve caused.
CSS Modules — CSS-In-JSX
CSS modules solve this in part by namespacing the style, but the main problem is that they make the code much less readable.
See how the Page component above is not very readable?
And even though we try to be semantic, it’s actually quite hard to see the meaning of each Element (e.g. addInvestorBtn) in the sea of code.
What if someone didn’t try hard enough to make their classnames semantic and put in something like .clicker? Now that truly would be difficult to understand.
Styled Components solves the issues of semantic, readable code, while maintaining unique namespacing. With styled components, you export your styles as a component from the styles file. E.g.
And now we just import them into the JSX file:
To my mind, this is so much easier to read, and just from looking at the components in Page.jsx, I can quickly determine what each one is supposed to do, even though they are nested.
Styled Components and Variables
Styled components allows us to pass variables to our styles as props
Styled Components and Inheritance
Another useful tool that Styled Components offers us is the ability to inherit or extend styles.
Styled Components and Theming
Styled Components allows us to easily theme our components by importing a theme file.
And now we can use them in our Styled Components file.
- Code is more often read than it is written
- As such, we need to make our code as readable and understandable as possible
- Styled Components helps us do this by naming our components in a very semantic way while avoiding messy code bloat.
- Styled Components also offers us useful tools like:
- variable injection via props
- style inheritance