0

I want to make checkbox mandatory field in react js.

I am new to reactjs but i have an idea that i should do it using length . Below is the code:

<CheckboxGroup name="zones" value={this.state.zones} onChange={this.handleCheckboxChange}>
       {(Checkbox) => (
         <>
                                                   
            {this.state.zones_to_render_to_render.map((zone, key) =>
              <Col key={key} lg="10">
                  <label >
                         <Checkbox value={zone.zone_id} />{zone.zone_name}
                  </label>
             </Col>
                                                            

          )}
                                                        
       </>
     )}
</CheckboxGroup>

How to check using length?

karthik
  • 21
  • 1
  • 8
  • Look at these answers https://stackoverflow.com/questions/32174317/how-to-set-default-checked-in-checkbox-reactjs . You can do it just using false/true. – Vova Aug 14 '20 at 07:08
  • It looks like you're using AntD. You can use their [Forms API](https://ant.design/components/form/) to accomplish this and handle the rest of the form's functionality, or look into a solution like [Formik](https://github.com/formium/formik) which can also handle validation for you. There is simply not enough code here to determine what making it "required" means yet. – Chris B. Aug 14 '20 at 07:08
  • You can use true/false to do that. You do not need to use length here. You can create a function, let's say: invalid() where you check whether your checkbox is checked or not. Then if invalid, do not submit the form, and you can show a pop up error. – Donald Shahini Aug 14 '20 at 07:12

1 Answers1

0

The component <Checkbox /> has a prop required which is false by default you can make the checkbox mandatory by passing it true.

<Checkbox value={zone.zone_id} required={true} />
  • It is making to select all the checkbox field. I want to select any 1 field. – karthik Aug 17 '20 at 03:43
  • In the map function, key is basically the index of the `zones`, you can conditionally make the checkbox mandatory by passing some condition to the required prop. Below are some examples: 1. To make the first checkbox mandatory, you ll have to do required={key === 0} 2. To make the last checkbox mandatory, you ll have to do required = {key === this.state.zones_to_render_to_render.length} – Awais Rafiq Chaudhry Aug 17 '20 at 05:10