lukeed / clsx

A tiny (239B) utility for constructing `className` strings conditionally.
MIT License
8.08k stars 141 forks source link

What is the purpose of this? #66

Closed Moucky closed 1 year ago

Moucky commented 1 year ago

Hi all, just using a starter project and some of the classes are added like this:

        clsx(
          'absolute right-0 flex h-full items-center', //
          'md:mr-4',
        )

Can anyone explain the purpose of this? Why not just do:

        clsx(
          'absolute right-0 flex h-full items-center md:mr-4',
        )
lukeed commented 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"
Moucky commented 1 year ago

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.

Moucky commented 1 year ago

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',
          ])}
lukeed commented 1 year ago

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.

Moucky commented 1 year ago

Thanks, I appreciate you clearing that up for me. I'll stick to this approach.