lukeed/clsxPublic

A tiny (239B) utility for constructing `className` strings conditionally.

What is the purpose of this?

MO

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', ) ```

  1. LU

    > 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.

    ```js 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" ```

  2. lukeedclosed3 years ago on GitHub

  3. MO
    Author

    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.

  4. MO
    Author

    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', ])} ```

  5. LU

    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.

  6. MO
    Author

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