data-* attributes for styling

I'm wondering what people's opinions are on this vs using multiple classes. I work mainly in react and use CSS modules and I feel in that context it makes sense. 1 base class and then modify that via data-* attributes. I think this will also be more powerful when the new attr() functionality hits all browsers and not just chrome. In React land there is no need for an extra dep to toggle various classes and the JSX looks a lot more readable. Also in the devtools I can then see what "state" my component is in via the data attributes. I guess I don't really see any downsides but I'm wondering if I'm overlooking something. As well as data attributes you can use aria attributes to help with accessibility and style based upon that.
3 Replies
ἔρως
ἔρως3mo ago
it depends it really depends on what you're trying to do if you want to set a theme to your html tag, using a data attribute is easier in js if you want to define a variant, maybe a class is better or utility classes too
Kevin Powell
Kevin Powell3mo ago
The main downside is that some people don't like it, and will complain 😅
ἔρως
ἔρως3mo ago
well, those people will complain because their shadow isn't bright enough on a dark night i like to use what fits best if i need to change it from js, at any point: data attribute

Did you find this page helpful?