lundi 18 novembre 2019

Formik checkboxes not changing values

I'm trying to create a form with Formik, which is essentially a series of check-boxes. Here is a simplified version of what I am doing,

I have some props looking like this:

"settings" : {
    "email_addresses":
    [
        "a@b.com",
        "c@b.com",
    ],
        "alerts":
    {
        "SYSTEM": {
            "UP": {
                "enabled": true,
                    "states": ["UP"]
            },
            "DOWN": {
                "enabled": false,
                    "states": ["DOWN"]
            }
        }
    }
}

Here is the form

...
return (
    <Formik
        initialValues={this.props.settings}
        onSubmit={(values) => {
            console.log('values', values)
        }}
    >
        {props => {
            return (

                <Form>
                    {
                        Object.keys(props.values.alerts).map((alert) => {
                            Object.keys(props.values.alerts[alert]).map((state) =>
                                <Field name={props.values.alerts[alert][state].enabled}>
                                    {({ field, form, meta }) =>
                                        <input
                                            type="checkbox"
                                            id={props.values.alerts[alert][state]}
                                            checked={props.values.alerts[alert][state].enabled}
                                        />
                                    }</Field>
                            )
                        }
                        )
                    }

                </Form >
            )
        }}
    </Formik >
)
...

When the page is rendered, check-boxes are correctly rendered and ticked/not ticked depending on the values of "enabled". What is not working is the behaviour when clicking on the checkbox. Tick is not added/removed and values are not changed.

I worked on the issue following two hypotheses:

  • Formik checkbox does not need an onChange/onClick/etc. function to handle this (as it proved to be the case for a couple of "text" fields in the same form).
  • Formik checkbox needs a function. Which I tried to add both within the tag and in the render() function. But without success.

Any idea where the problem might be?




Aucun commentaire:

Enregistrer un commentaire