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'
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
Answers
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
ornull
or any value not allowed for margin, all is good.style vs styled-components
Two Scenarios:
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.
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
**