Correct way to support multiple checkboxes with same name
See original GitHub issueDescribe the question?
What’s the ‘correct’ way to support multiple checkboxes, where the user can pick one or more values in the same group? E.g., pick zero or more colors.
To Reproduce
In pure HTML I’d write inputs with the same name:
<input type="checkbox" name="colors" value="red">
<input type="checkbox" name="colors" value="green">
<input type="checkbox" name="colors" value="blue">
In react-hook-forms, how would I get the list of checked colors back as a list?
The obvious solution is to copy the above with the same name, but that doesn’t produce the correct value. However, this just produces the value of the first checkbox (checked or not).
// Doesn't work
rainbow.map(
(c,i) => <label key={c}><input type="checkbox" value={c} name="sameName" ref={register} />{c}</label>
)
A working solution is to trick react-hook-forms into make the name an array, e.g., colors.0
, which gives me an array of the checked checkboxes, but this feels like a hack.
// Produces the correct outcome
rainbow.map(
(c,i) => <label key={c}><input type="checkbox" value={c} name={"withIndex."+i} ref={register} />{c}</label>
)
Codesandbox link https://codesandbox.io/s/react-hook-form-multiple-checkboxes-u95u2
Left-hand-side shows using the HTML style same name; clicking Submit just returns the value of the first checkbox.
Right-hand-side shows using a fake index, which appears to work correctly.
Additional context (in my real app, the list of values is very dynamic)
Issue Analytics
- State:
- Created 4 years ago
- Reactions:6
- Comments:36 (14 by maintainers)
@bluebill1049 as above, I really think ‘how to handle checkboxes’ should be in the getting started or FAQ docs…
Please could you reopen this?
Totally agree, there’s no mention of how to handle a group of checkboxes the “right” way anywhere in the documentation. I think it would be immensely useful to have an example in the getting started section.