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.
To control the mode of input element define readOnly attribute with it and control it's value by state variable, Whenever you update the state value react will re-render the component and it will change the mode on the basis of state value.
state { condition: true } return ( <Button {... (condition ? {className: 'btn btn-primary'} : {})} /> ); Depending on the value of condition either the {className: 'btn btn-primary'} or {} will be returned. The Spread Operator will then spread the returned object properties to the Button component.
By using spread attributes, you can dynamically add (or override) whatever attributes you'd like by using a javascript object instance. In my example above, the code creates a disabled key (with a disabled value in this case) when the disabled property is passed to the Hello component instance.
When you use any React component you can pass it some input data that you want it to work with. These properties are called "props" and are read-only values that define the basic starting point for a component.
<input readOnly={this.props.boolean} />
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With