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?

3
  • Look at these answers stackoverflow.com/questions/32174317/… . You can do it just using false/true. Commented Aug 14, 2020 at 7:08
  • It looks like you're using AntD. You can use their Forms API to accomplish this and handle the rest of the form's functionality, or look into a solution like Formik which can also handle validation for you. There is simply not enough code here to determine what making it "required" means yet. Commented Aug 14, 2020 at 7: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. Commented Aug 14, 2020 at 7:12

1 Answer 1

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} />
Sign up to request clarification or add additional context in comments.

2 Comments

It is making to select all the checkbox field. I want to select any 1 field.
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}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.