compiled icon indicating copy to clipboard operation
compiled copied to clipboard

Ignore rule if value is not conditionally defined

Open pancaspe87 opened this issue 2 years ago • 0 comments

Is your feature request related to a problem? Please describe. When using a ternary operator to conditionally apply CSS Compiled will generate either

  • a blank CSS variable (if undefined) OR
  • a not valid CSS declaration ( if empty string)

This seems to happen only for object syntax

const Component = styled.div({
 background: 'white',
 position: iStickyHeaderEnabled() ? 'sticky' : undefined,
 top: iStickyHeaderEnabled() ? 0 : '',
});

Describe the solution you'd like We should ignore rules if the value is undefined or empty string.

Workaround

  1. Use spread operator
const Component = styled.div({
 background: 'white',
 ...(isStickyHeaderEnabled() && { 
  position: 'sticky',
  top: 0,
 })
});
  1. use the default value.
position: isStickyHeaderEnabled() ? 'sticky' : 'static',

Need to ensure position is not set somewhere else.

  1. use template
styled.div`
   ${isStickyHeaderEnabled() ? 'position: sticky' : ''}
`

However, template literals are not recommended

pancaspe87 avatar Jun 07 '22 05:06 pancaspe87