Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't i check Formik checkboxes?

Tags:

reactjs

formik

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>)
}
like image 759
Nuzurie Avatar asked Oct 21 '25 09:10

Nuzurie


1 Answers

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()}/>
like image 97
Lahiru Avatar answered Oct 27 '25 05:10

Lahiru