twind icon indicating copy to clipboard operation
twind copied to clipboard

Conditional classes and tw function not working as expected

Open lloydjatkinson opened this issue 2 years ago • 4 comments

I have a component with a series of props for margin and padding. I am trying to prevent undefined being written to the DOM which is happening with the following code:

// value is either a number, or an object { sm: number, md: number: number, etc... }
return tw(
    `sm:${prefix}-${value.sm}`,
    `md:${prefix}-${value.md}`,
    `lg:${prefix}-${value.lg}`,
    `xl:${prefix}-${value.xl}`,
    `2xl:${prefix}-${value['2xl']}`,
);

Which results in the following where properties that are not specified in the object result in undefined:

<div class="sm:m-2 md:m-8 lg:m-16 xl:m-20 2xl:m-undefined sm:p-4 md:p-8 lg:p-12 xl:p-16 2xl:p-undefined"> Box Component </div>

I'd like to remove these undefined values so I tried the following:

const test = tw({
    [`sm:${prefix}-${value.sm}`]: value.sm,
    [`md:${prefix}-${value.md}`]: value.md,
    [`lg:${prefix}-${value.lg}`]: value.lg,
    [`xl:${prefix}-${value.xl}`]: value.xl,
    [`2xl:${prefix}-${value['2xl']}`]: value['2xl'],
});

console.info(test);
return test;

However this results in an empty string totally. How can I write these conditionals correctly?

I think the screen() function would probably be better here but not sure if it would work based on the value being dynamic?

lloydjatkinson avatar Apr 04 '22 14:04 lloydjatkinson

Are you using v0 or v1 of Twind?

IgnusG avatar Apr 04 '22 14:04 IgnusG

"twind": "^0.16.16",

lloydjatkinson avatar Apr 04 '22 14:04 lloydjatkinson

I think I found the problem, the right hand side MUST be a boolean and be true in order for this to work so something like:

{
  [`sm:${prefix}-${value.sm}`]: value.sm ? true : false,
  ...
}

Or shorter:

{
  [`sm:${prefix}-${value.sm}`]: value.sm && true,
  ...
}

Anything other than true evaluates to false. Maybe this should be loosened to comparing truthy vs falsy values. I'm not sure if this isn't already the case in v1 (alpha).

IgnusG avatar Apr 04 '22 14:04 IgnusG

Thanks. I'll add a test case and check with the v1 branch.

sastan avatar Apr 23 '22 05:04 sastan

This works in v1 with cx and tx.

sastan avatar Oct 04 '22 15:10 sastan