4

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?

1
  • I've had luck using ternaries outside if the element, something like this: const attribute = true ? {id: test} : {}; <input {...attribute}/> Commented Feb 18, 2021 at 16:35

3 Answers 3

2

You can do:

<input type='text' {...(condition ? {id: 'test'} : {})} />
1
  • 1
    perfect, that method work withs with &&. Thanks Commented Feb 18, 2021 at 16:47
2

You can also do:

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

1

You can do something like this:

const props = {
  type: 'text'
}

if (condition) props.id = 'test'

return <input {...props} />

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.