user8758206
user8758206

Reputation: 2191

Conditional react attributes

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?

Upvotes: 4

Views: 757

Answers (3)

jperl
jperl

Reputation: 5112

You can do something like this:

const props = {
  type: 'text'
}

if (condition) props.id = 'test'

return <input {...props} />

Upvotes: 1

medzz123
medzz123

Reputation: 229

You can also do:

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

Upvotes: 2

Ajeet Shah
Ajeet Shah

Reputation: 19813

You can do:

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

Upvotes: 2

Related Questions