I'm trying to create a simple Formik form. First time working with checkboxes. I can render the checkboxes, but am unable to check any of them. What's the problem?
export default function App() {
var lights = [{id:1, name:"a"}, {id:2, name:"a"}]
return (<div>
<h1>Select Lights</h1>
<Formik
initialValues={{
checked: [],
}}
onSubmit={(eve) => this.submit(eve)}
>
{({values}) => (
<form>
<div id="checkbox-group">Checked</div>
<div role="group" aria-labelledby="checkbox-group">
{lights.map((light) =>
<div>
<label>
<Field type="checkbox" key={light.id} name="checked" value={light.id}/>
{light.name}
</label>
</div>
)}
</div>
<button type="submit" onClick={(event => this.submit(event))}>Submit</button>
</form>
)}
</Formik>
</div>)
}
Checkbox value being a number seems to be the problem. Because you initialise it as a number but internally it's converted to a string when formik is tracking the checkbox value. Change
<Field type="checkbox" key={light.id} name="checked" value={light.id}/>
to:
<Field type="checkbox" key={light.id} name="checked" value={light.id.toString()}/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With