Ad

Formik Checkboxes Not Changing Values

- 1 answer

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":
    [
        "[email protected]",
        "[email protected]",
    ],
        "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?

Ad

Answer

It turns out that the syntax I used, which I found in a number of examples, is unnecessarily complicated for what I needed to do.

Another issue was the way I was defining the 'path' to the values for 'name'. It seems that as I have assigned props.settings to initialValues then I just need to indicate the relative path.

Using the following simple syntax, it worked immediately.

<Field name={`alerts[${alert}][${state}].enabled`} type="checkbox" />
Ad
source: stackoverflow.com
Ad