Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 730
Pavindu Avatar asked Oct 18 '25 12:10

Pavindu


1 Answers

In the html part, you can do something like:

 <Form.Control name="length" defaultValue={this.state.length} required={ this.state.category==='roll'}/>
like image 189
Deepak Avatar answered Oct 21 '25 19:10

Deepak