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:
- 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?
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" />
Related Questions
- → Import statement and Babel
- → should I choose reactjs+f7 or f7+vue.js?
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → .tsx webpack compile fails: Unexpected token <
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → React Native with visual studio 2015 IDE
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → How do I determine if a new ReactJS session and/or Browser session has started?
- → Alt @decorators in React-Native
- → How to dynamically add class to parent div of focused input field?