Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the best way to conditionally add readOnly in React?

Tags:

reactjs

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.

like image 630
Shawn Matthews Avatar asked Mar 19 '18 03:03

Shawn Matthews


People also ask

How do you add readOnly attributes in React?

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.

How do I add a condition to an attribute in React?

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.

How do you add HTML attribute dynamically in React?

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.

Are Props readOnly React?

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.


2 Answers

<input readOnly={this.props.boolean} />
like image 82
J Livengood Avatar answered Sep 21 '22 19:09

J Livengood


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...

like image 44
Ross Attrill Avatar answered Sep 20 '22 19:09

Ross Attrill