New "data attribute variants" let you style elements based on a specific data attribute value
We have three callout elements here, and the only difference really between all of these is the background color and the text color. You can imagine we could build a callout component that would have a prop called status, and then you would pass this prop to handle the styles. Well, what if instead of a status prop, the differentiator here was a data attribute?
So take a look at this. We have a callout component here, and we're using this callout component three times, passing a data status prop, which can be success, warning, or danger. The component renders the exact same HTML with the same styles as before.
So the only problem, obviously, is that the three callouts are now green, and we need to use this data status attribute to handle the styles. We're going to use the new data attribute variants added to Tailwind 3.2 to handle this. So here where I have BG green 200, I will prefix this with a data attribute variant, data dash square brackets.
So we want to target the data status when this attribute's value is equal to success. And so now only the first callout is green because our first callout here has data status set to success. So let's do the same for the other two callouts. Data status equals warning.
In that case, we want BG yellow 200. And finally, data status equals danger, BG red 100. Nice. So that's working really well. Obviously, the text inside is still green 800, so we need to do that now.
And you might think we could do something like data status success, text green 800. But as you can see now, all text is black. And this is because this element does not have a data status attribute. This parent element does.
So on the parent here, I will add a class of group. And this will allow me to now have a group data attribute variant. And you can see that it's targeting the group where the data status is success. Group data status equals warning, text yellow 800.
And group data status, danger, then give us text red 800. And there you have it.
We've styled our callout components based on the data attribute passed with a pretty cool technique to know.