Using CSS Variables with React

As react developers we have to change CSS of the component as a response to props or state change.
One of the popular solution is an approach called “CSS-in-JS” and the libraries like “styled-components”.
You can read more about it in the awesome “All You Need To Know About CSS-in-JS” article.

Also we can write inline CSS in the component, but I don’t like to do that because I keep CSS rules not only in the .css file where I expect them, but also in the random places within the .jsx and inline styles are hard to override from the other places.

In this article I would like to show you what I found intresting recently when I was reading about CSS Variables.
I don’t want to explain this topic in details because there are better places to learn:
- “What is the difference between CSS variables and preprocessor variables?
- Almost one hour speech by Lea Verou:

One thing I want to highlight here is that, unlike variables we are used to use in SASS, we can modify custom properties in JS, because they are interpreted in the browser at runtime.
So we can create a CSS variable I the :root pseudo selector which contains, for example, a background color of the component:

:root {
— mycomponent-bg-color: orange;

Then, we can change the value of the variable in the component when the state will change:

componentDidUpdate() {
‘ — mycomponent-bg-color’,

I created a simple demo where we can control rotation of the image:

So the custom properties works like an API which CSS expose to JS.

Ok, but still, why don’t use just an inline style?

What I like in example above is:
1. Clear separation between CSS and JS;
2. We can use component state represented by variable in many places in the CSS;
3. The code of the component is much cleaner without those lines of inline CSS

This is only an experiment I created during the learning process, so I am curious what do you think about this idea, and why it could be bad ;)

Web developer | React