Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I set an input field to readonly in React while keeping my onChange function?

I have the following React render function:

render: function() {
  return <input type="text" name="my-input-field" value={this.state.myObject} onChange={myFunction} />;
}

I would like to have this input field be readonly upon some condition that I have checked for. My understanding is that this input field would default to readonly if I didn't have the onChange function. Simply adding the readOnly tag hasn't worked for me.

How can i rewrite this so that I can later change the readonly status?

like image 241
jrader Avatar asked Aug 13 '15 20:08

jrader


People also ask

How do you make the input field Uneditable in react?

You can make the TextBox as read-only by setting the readonly attribute to the input element.

How do I delay onChange event?

You can change the trigger delay of an "On Change", by setting the osOnChangeTimerDelay javascript variable. The default value is 800, that corresponds to a delay of 800 ms after the user stops typing.

Why is the input field not editable in react?

You need to add an onChange event and then set the shop_profile_data.NAME to a different value. Then the value of the input will change. If you only want to set the initial value of the input , use defaultValue property (docs). defaultValue will set the initial value, but then allow the value to be changed.


1 Answers

You can use spread attributes to do that:

render: function() {
  var opts = {};
  if( /* here your condition */ ) {
      opts['readOnly'] = 'readOnly';
  }

  return (
    <input 
      type="text" 
      name="my-input-field" 
      value={this.state.myObject} 
      onChange={myFunction} 
      {...opts} 
    />
  );
}
like image 153
gusgol Avatar answered Oct 19 '22 23:10

gusgol