Nuzurie
Nuzurie

Reputation: 143

Why can't i check Formik checkboxes?

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>)
}

Upvotes: 4

Views: 1620

Answers (2)

In my case have I use useEffect below:

  useEffect(() => {
    formik.resetForm()
    formik.setValues({
      ...formik.values,
      link: link.link,
      restrito: Boolean(link.restrito),
    })
  }, [link])

in that case link it the props, and in check box i use this for change value of checkbox:

   <Checkbox
      {...formik.getFieldProps("restrito")}
      checked={formik.values.restrito ? true : false}
      onClick={() => formik.setFieldValue("restrito", !formik.values.restrito)}
      label="Restrito"
    />

Upvotes: 0

Lahiru
Lahiru

Reputation: 186

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()}/>

Upvotes: 7

Related Questions