Conditional react attributes

Viewed 150

I've had a look at some other posts but nothing seems to address only including an attribute if a condition is met rather than give another value if the condition is false.

I'm trying to only add an attribute if a condition is met. Take this for example:

<input {{true && id='test'}} type='text'/>

I've just put true instead of the real condition for ease, so this input should have an id of true. What is the workaround for this?

3 Answers

You can do:

<input type='text' {...(condition ? {id: 'test'} : {})} />

You can also do:

<input {...(hello && { id: 'test' })} />

You can do something like this:

const props = {
  type: 'text'
}

if (condition) props.id = 'test'

return <input {...props} />

Related