How to style using data attributes
tailwindcssjavascript
Suppose you are using a Callout component like this:
<>
<Callout data-status="success">Some success message</Callout>
<Callout data-status="warning">Some warning message</Callout>
<Callout data-status="error">Some error message</Callout>
</>
You can style your Callout
component doing this:
function Callout({children}) {
return (
<div className={clsx(
"p-4",
"font-medium",
"rounded-lg",
"data-[status=success]:bg-green-200"
"data-[status=warning]:bg-yellow-200"
"data-[status=error]:bg-red-200"
)}>
<p className="text-green-800">
{children}
</p>
</div>
);
}
You can combine this with the group
class to also styling nested elements based on the container.
Then, the resulting code will look like this:
function Callout({children}) {
return (
<div className={clsx(
"group", // Add the group class
"p-4",
"font-medium",
"rounded-lg",
"data-[status=success]:bg-green-200"
"data-[status=warning]:bg-yellow-200"
"data-[status=error]:bg-red-200"
)}>
<p className={clsx(
"group-data-[status=success]:text-green-800",
"group-data-[status=warning]:text-yellow-800",
"group-data-[status=error]:text-red-800",
)}>
{children}
</p>
</div>
);
}
I saw this from Simon Vrachliotis
I learnt this from @simonswiss