Alessandro
Alessandro

Reputation: 165

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":
    [
        "[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:

Any idea where the problem might be?

Upvotes: 0

Views: 4212

Answers (1)

Alessandro
Alessandro

Reputation: 165

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" />

Upvotes: 1

Related Questions