0

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

What code example would be the best? Can we use non css values?

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

1
  • Make sense to use 'initial' in that case because it is css supported value for this property. But is it bad to use: '', false, null, undefined, none? Commented Mar 20, 2024 at 15:33

1 Answer 1

1

I personally prefer using a separate class for isOpen state and conditionally applying the className rather than using inline styles. The classnames package can be used for conditionally applying the class to the element.

However, if you want to use the alternative approach, I find the following method simpler and easier to understand:

 <p style={{ color: "dodgerblue", ...(isOpen ? { margin: "10px" } : {}) }}>
    ...
 </p> 

Sandbox Example

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.