twind
twind copied to clipboard
Conditional classes and tw function not working as expected
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?
Are you using v0 or v1 of Twind?
"twind": "^0.16.16",
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).
Thanks. I'll add a test case and check with the v1 branch.
This works in v1 with cx
and tx
.