Closed Moucky closed 1 year ago
for constructing
className
strings conditionally.
Conditional concatenation.
If your usage only involves known static strings, then yes there's no point. But if you have logic tied to the existence/usage of a class, then something like clsx
is suited for this.
let run = () => clsx('foo bar', isBAZ && 'baz', { active: isActive });
let isBAZ=false, isActive=true;
run(); //=> "foo bar active"
isBAZ=true, isActive=false;
run(); //=> "foo bar baz"
isBAZ=true, isActive=true;
run(); //=> "foo bar baz active"
Thanks Luke, my example is exactly as it's written in the project. Could it just be a developer preference to write it that way?
I just want to make sure there isn't a point to it before I change things.
Here's another example:
className={clsx([
'hidden h-[2.4rem] items-center rounded-sm bg-darkGray bg-opacity-0 p-2',
'lg:flex',
'hover:bg-opacity-10',
])}
Looks like they did it for visual grouping. AKA, keeping all base Tailwind classes in the first line/group, then size modifiers together, then state modifiers.
clsx is really fast at concatenating string arguments together, so there's not a massive penalty here.
Thanks, I appreciate you clearing that up for me. I'll stick to this approach.
Hi all, just using a starter project and some of the classes are added like this:
Can anyone explain the purpose of this? Why not just do: