Jack-Edward Oliver

Senior Design Technologist @ CloudBees.
Find me on LinkedIn / Twitter / Github. Or you can email me.

Swapping class attributes for data-* attributes when writing state-based styles.

These days working primarily in React or JS SPA frameworks I find I have two options for handling state-based styling.

Emotion / CSS-in-JS

Easy-peasy, inject the style change directly into the SerializedStyle block, and it will update whenever the state does.

or Plain ol' CSS, anything pre-processed (SCSS etc)

If I'm using vanilla CSS or SCSS/SASS – the following property method is my preferred way of handling state-based styling.

So, the most straightforward route here would be to add any state-based styling into a class (maybe isActive?), and tack it on to the existing CSS classes in your HTML markup. Job done?

Alas, I've found over time this is not great, and can get messy very quickly. Here's an example.

The "class" way

When isActive is not there, I don't know that it should be.

<div class="foo isActive">...</div>

It feels like a black box and it's hard for me to figure out what states the UI might be in at a glance. In my humble opinion, this is more declarative:

The "data-*" way

<div class="foo" data-active="true">...</div>

The key to this implementation is that in the event data-active or data-children is false – then I can see it, alongside gaining the knowledge that at some point, it might not be.

For example:

<div class="foo">...</div>
<div class="foo" data-active="false">...</div>

When handling states that can be composed from multiple permutational values, I have found this to be more manageable. YMMV :-)

© 2022 Jack-Edward Oliver
Made in 🇸🇪