DEV Community

Cover image for Data-* attributes instead of if-else statement for styling component states
Dương
Dương

Posted on

1

Data-* attributes instead of if-else statement for styling component states

First thing first

Hello fellow devs, I am Duong, a Fullstack developer. Yesterday (at the time I wrote this), I discovered a new way to style Component states with CSS, thus I want to share it with everybody. Let's go.

Problem

Suppose we have a button with a loading state, usually, we will style it as below:

// Button.js
const Button = ({children, loading}) => {
   // other code...
   // If you use classNames it would be like this:
   // className={cx('other class go here', {['loading']: loading})}
   return <button className={`other class go here ${loading ? 'loading' : ''}`}>{children}</button>
}
Enter fullscreen mode Exit fullscreen mode
/* button.css */
.loading {
    ...CSS properties
}
Enter fullscreen mode Exit fullscreen mode

But I have found a new way for this with the data-* attributes. Before diving into the code, we need to know what data-* attributes is.

According to MDN docs:

The data-* global attributes form a class of attributes called custom data attributes, that allow proprietary information to be exchanged between the HTML and its DOM representation by scripts.

So we could create a custom attribute with it and leverage these attributes for our CSS selector.

// Button.js
const Button = ({children, loading}) => {
   // other code...
   return <button className={`other class go here`} data-loading={loading}>{children}</button>
}
Enter fullscreen mode Exit fullscreen mode
/* button.css */
button[data-loading="true"] {
   // CSS properties...
}
Enter fullscreen mode Exit fullscreen mode

With this approach, we won't need an if-else statement or classNames library at all. Moreover, it is easier for us to test the button state because we can use the selector button[data-loading="true"] to select the dom element.

In the code example above, I use React, but since this is a native feature of HTML so we can use it for every frontend framework out there. I will leave a stackblizt sandbox here so you could play with it

Now you've known another way to style your component. Hope this is useful for you

References:

  1. W3schools documentation about data-* attributes
  2. MDZ documentation about data-* attributes

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay