Search code examples
reactjsformsrequired

Conditionally make an input required in React


In a form in My React app,I want to make a set of inputs(Length & Gauge) required,if the Category is set to roll.How can I do that?Thanks in advance.

 <Form.Group as={Col}>
   <label>Category</label>
   <Form.Control
     as="select"
     name="category"
     defaultValue={this.state.category}
     onChange={this.catControl}
   >
    <option>printed</option>
    <option>roll</option>
  </Form.Control>
</Form.Group>

<Form.Row>
 <Form.Group as={Col}>
   <label>Length(cm)</label>
   //required if category is set to "roll". How can I do that?
   <Form.Control name="length" defaultValue={this.state.length} />
 </Form.Group>

 <Form.Group as={Col}>
   <label>Gauge(mm)</label>
   <Form.Control name="gauge" defaultValue={this.state.gauge} />
 </Form.Group>
</Form.Row>

Solution

  • In the html part, you can do something like:

     <Form.Control name="length" defaultValue={this.state.length} required={ this.state.category==='roll'}/>