16

In React given a prop that provides true/false how would one conditionally add readOnly to an input field in JSX?

So if I had this.props.boolean whats a terse option for adding readOnly when this.props.boolean == false readOnly isn't attached, when this.props.boolean == true readOnly is attached.

SandroMarques
  • 5,029
  • 39
  • 40
Shawn Matthews
  • 1,652
  • 1
  • 13
  • 21

2 Answers2

28
<input readOnly={this.props.boolean} />
J Livengood
  • 2,580
  • 1
  • 11
  • 26
4

This is ugly but it works:

{props.readonly ?
    <input placeholder="Can't edit here" readOnly />
    :
    <input placeholder="edit here..."/>
}

Make the two controls custom to avoid duplicating as much as possible...

Ross Attrill
  • 2,446
  • 1
  • 21
  • 28