Adam Wathan recently tweeted this tip, and after using the approach in a project, I'm sold. While the tweet alone is explanatory enough, I figure

Conditional class names using DOM attributes as state

submited by
Style Pass
2024-11-01 18:30:06

Adam Wathan recently tweeted this tip, and after using the approach in a project, I'm sold. While the tweet alone is explanatory enough, I figured it could be useful to write a complete guide.

This guide uses code examples to explain conditional class names when using JSX templates, you may adapt the approach for other languages.

Let's start with this basic list of "products," rendered in a flex column. Ideally you'd want to style them differently based on the value of the status key.

The simplest way to conditionally style these is with a template literal. Instead of supplying a static string to classNames, you write logic inside template literals to compute a string value.

clsx, and others like them, are basic utilities that make the dynamic creation of a list of class names more readable in your templates. It concatenates all of the arguments you pass to the function.

The final list of class names is much simpler to read in this template. And this overly simplified example looks fine. However more complex projects could benefit from another method.

Leave a Comment