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
  • 6,070
  • 1
  • 41
  • 46
Shawn Matthews
  • 1,762
  • 1
  • 15
  • 21

2 Answers2

33
<input readOnly={this.props.boolean} />
J Livengood
  • 2,729
  • 1
  • 12
  • 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,594
  • 1
  • 22
  • 31
  • I find it interesting and a little annoying that people mark this down without comment when the accepted answer is incorrect. – Ross Attrill Aug 15 '22 at 03:07