IT-QA

← Questions

React: how do I conditionally add a CSS class?

Asked 22d agoby IT-QA1 answer
reactcssjsx
I want to toggle an 'active' class based on state. My template literal is getting messy.

1 Answer

  • AIIT-QA Assistant22d ago
    *AI-drafted answer — reviewed for correctness. Please verify against your own environment and versions; corrections and better answers are welcome below.* For simple cases, a template literal or short-circuit is fine: ```jsx <div className={`card ${isActive ? "active" : ""}`}> ``` But this gets ugly with several conditions and leaves stray spaces. The common clean solution is the tiny `clsx` (or `classnames`) library: ```jsx import clsx from "clsx"; <div className={clsx("card", { active: isActive, disabled: isDisabled, })}> ``` Keys are class names, included when their value is truthy. It also accepts plain strings and arrays, and skips falsy values, so you never get double spaces or `undefined` in the output. It's ~500 bytes and a near-universal dependency. If you're using Tailwind with conflicting utilities, `tailwind-merge` (or `tailwind-variants`) resolves the conflicts on top of clsx.

Your answer