lukeed / clsx

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

Combine variables without spaces #54

Closed longevitytina closed 1 year ago

longevitytina commented 1 year ago

Hi! Is there a way to have conditional variables add onto the class string without spaces? If there is a way, I'm not understanding implementation from documentation.
Want to update the state, but cannot do this if a spaces exists. Current expected behavior:

<div className={ clsx( 'foo barr example_',
      {
        'zoo': !place,
        [place as string]: place
      }
    )}>
// 'foo barr example_ zoo'

Desired behavior:

<div className={ clsx( 'foo barr', 'example_' +
      {
        'zoo': !place,
        [place as string]: place
      }
    )}>
desired output // 'foo barr example_zoo'
actual output // 'foo barr example_[Object Object]'

I can have a crack at contributing if something like this doesn't exist! Thanks for any info or for a work around.

lukeed commented 1 year ago

You have to wrap the object in a clsx call. What you pasted in the second snippet natively evaluates to “example_[object Object]” before clsx even sees it

longevitytina commented 1 year ago

Thanks for the quick response! Brilliant, I didn't realize that was possible. This worked like a charm:

<div className={ clsx( 'foo barr', 'example_' +
      clsx({
        'zoo': !place,
        [place as string]: place
      })
    )}>
output // 'foo barr example_zoo'
lukeed commented 1 year ago

Haha great, glad that was it