Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you conditionally disable a form input in react?

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.

like image 857
Ana Isabel Avatar asked Feb 21 '18 23:02

Ana Isabel


People also ask

How do I disable input field based on condition in React?

How do you disable an input in react? Disable the TextBox by adding the e-disabled to the input parent element and set disabled attribute to the input element.

How do I turn off a form in React?

We can disable a button with React by setting the disabled prop of the button. We pass in the value state to let us enter the data that we want into the input field. Then we check that in disabled prop of the button. This way, the button is disabled if we have nothing inputted into the form field.

How do you toggle a disabled attribute in React?

Disabled is an attribute passed to React buttons. This means that it is passed into button components within JSX. function App() { function button1Click() { console. log('1click') } function button2Click() { console.


1 Answers

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}
      />
   );
 }
like image 128
Jamie Hutber Avatar answered Sep 20 '22 23:09

Jamie Hutber