- The file is big
- The file might look unmaintainable:
- You have to update the class map & the enum (spoiler: TypeScript will ensure this is in sync)
- There is a lot of duplicate code (the classNames per variant are almost the same except for the color)
- You know the exact states your component can be in
- There is no cleverness / dynamic classes going on -> More maintable
- There is no
className
prop, this means that we know what states / variants our component can be in, we don't introduce new implicit states (a large badge if we addclassName="text-xl"
) - If one of the values need an extra class, you can add it, no need for clever tricks. (E.g.: Let's say a yellow color needs a darker text color)
- PurgeCSS can easily remove non-used css classes
Here is a bad example: https://gist.github.com/RobinMalfait/7cf7a0498039027a1d591f5f2b908a95
Hey, thanks for the gist. Landed here from Tailwind GitHub.
Since we're using TypeScript, is it safe to assume that consumer of this components would also likely be using TypeScript?
If so, we can ditch the
enum
and defineVariant
as union type (it's usually recommended to useunion types
overenum
in TypeScript).Even better (single source of truth) if you just go for
as const
arrays.Here's how I'd define the same:
Benefit is that at the call-site when a consumer is consuming the component, they get autocomplete on the string values
"red"
,"green"
etc., and they don't have to know aboutBadge.variant
object. It reduces surface area of the API.If a new variant is to be added or an existing one needs to be removed / updated; only the array
variants
need to be modified, and TypeScript would do the rest.There's one loose end with this: the
variantMap
might not be exhaustive. As in, it might not create record values for all variants, only a subset of it.I don't know of a way to enforce this in TypeScript as of version 4.3.5. If this were a more type-safe language, like Elm or ReasonML, we could've used a function that takes variant as a parameter and returns a set of
TailWindCSSClassnames
, with aswitch-case
implementation. We could probably do a hack like this.Interested in hearing your thoughts.