- 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
classNameprop, 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
enumand defineVariantas union type (it's usually recommended to useunion typesoverenumin TypeScript).Even better (single source of truth) if you just go for
as constarrays.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.variantobject. 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
variantsneed to be modified, and TypeScript would do the rest.There's one loose end with this: the
variantMapmight 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-caseimplementation. We could probably do a hack like this.Interested in hearing your thoughts.