How do you conditionally disable a form input in react?

Ana Isabel picture Ana Isabel · Feb 22, 2018 · Viewed 13.8k times · Source

I would like to disable the validated input if an item meets a certain criteria. In this case if a product has a promotion.

Ideally I would like to do something like this:

<ValidatedInput
  className='product-dropdown'
  onChange={this.onProductChange.bind(this)}
  defaultValue={example.product_id}
  componentClass='select'
  name='product_id'
  placeholder='select'
  disabled={isDisabledInput}
 >

isDisabledInput {
  if(example.has_a_promotion) {
     return true
  }
}

I am using react-bootstrap-validation.

Answer

Jamie Hutber picture Jamie Hutber · Feb 22, 2018

This actually has nothing to do with react `per-say.

I have changed example to use the components state this will mean the ValidatedInput will re-render whenever the state is changed. This might not actually be necessary if example.has_a_promotion is correct when the component is rendered. So please change accordingly.

disabled is actually just a property that is passed down to the ValidatedInput component. Which means its value is just like any other js that is run when its wrapped with {}... so a simple if statement will do the trick.

 render(){
  return(    
     <ValidatedInput
       className='product-dropdown'
       onChange={this.onProductChange.bind(this)}
       defaultValue={example.product_id}
       componentClass='select'
       name='product_id'
       placeholder='select'
       disabled={this.state.example.has_a_promotion === true ? true : false}
      />
   );
 }