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>
}
/* button.css */
.loading {
...CSS properties
}
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>
}
/* button.css */
button[data-loading="true"] {
// CSS properties...
}
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
Top comments (0)