CSS properties with conditional styles and falsy values

66 Views Asked by At

I'm looking for the answer to the question how should I use styles with conditional operators.

What code example would be the best? Can we use non-CSS values such as undefined, null, false, etc.?

margin: isOpen ? '10px' : undefined
margin: isOpen ? '10px' : 'initial'

enter image description here

Is it okay to use it in that way? (so we pass 'undefined' and 'null' as a css property)

margin: isOpen ?? '10px'

and one more (so we pass every falsie value)

margin: isOpen && '10px'

or maybe this

margin: isOpen ? '10px' : ''

As context we can say we wanna use it in react style porp, or in styled-components

2

There are 2 best solutions below

0
Manny Alvarado On

Use unset to reset the property to its inherited value. More on the subject here:

https://developer.mozilla.org/en-US/docs/Web/CSS/unset

The way you design your if else statement would be unopinionated, as long as you don't set an undefined or null or any value not allowed for margin, all is good.

1
koundinya Pidaparthy On

style vs styled-components Two Scenarios:

  1. If you are creating Components where you are going to reuse it. Such as Material UI Textfield components (Commonly same component used for entire project ) in this scenario go with styled components.

  2. If you are using any div or span or any element for specific UI. Which is for a single specific task and you are sure that you are not going to reuse. Then probability go with style tag. And if you want to you can also uses classes and make sure that css class is not defined at 2 styles.css files.

margin: isOpen ? '10px' : undefined

instead of undefined use 'unset' so that in future you can check the details via developer tools if required.

margin: isOpen ?? '10px'

Never use this what if you get isOpen as true

then margin is true which is a invalid property

margin: isOpen && '10px'

never use && what if isOpen is null. again invalid property

** go with unset which would be a best option

margin: isOpen ? '10px' : 'unset'

**