I have an existing form, using, using a custom component that is working under formik-material-ui 1.0:
const MyCheckbox = ({ field, form, label, ...rest }) => {
const { name, value: formikValue } = field
const { setFieldValue } = form
const handleChange = event => {
const values = formikValue || []
const index = values.indexOf(rest.value)
if (index === -1) {
values.push(rest.value)
} else {
values.splice(index, 1)
}
setFieldValue(name, values)
}
return (
<label>
<Checkbox onChange={handleChange} checked={formikValue.indexOf(rest.value) !== -1} {...rest} />
<span>{label}</span>
</label>
)
}
and being rendered using this line:
<Field component={MyCheckbox} name="sectionChoices" value={label} label={label} />
As described by the documentation I've removed the Field
import, and the component
property, but the remainder has me stuck. If Field is no longer available, what should I be doing in the MyCheckbox
? I've tried:
import { Formik, Form, useForm } from 'formik'
const MyCheckbox = ({ field, label, ...rest }) => {
const { name, value: formikValue } = field
const form = useForm()
const { setFieldValue } = form
const handleChange = event => {
const values = formikValue || []
const index = values.indexOf(rest.value)
if (index === -1) {
values.push(rest.value)
} else {
values.splice(index, 1)
}
setFieldValue(name, values)
}
return (
<label>
<Checkbox onChange={handleChange} checked={formikValue.indexOf(rest.value) !== -1} {...rest} />
<span>{label}</span>
</label>
)
}
But I get this error:
Attempted import error: 'useForm' is not exported from 'formik'.
My package.json
file has the following relevant dependencies:
{
"dependencies": {
"@material-ui/core": "^4.5.1",
"@material-ui/icons": "^4.5.1",
"formik": "^2.0.3",
"formik-material-ui": "^2.0.0-alpha.3",
"react": "^16.10.2",
"react-dom": "^16.10.2",
"react-router-dom": "^5.1.2",
"react-scripts": "3.3.1",
"recompose": "^0.30.0",
"typeface-roboto": "^0.0.75",
"yup": "^0.28.1"
},
...
Migration instructions:
As stated about, I've using the migration instructions fromhere, a screenshot from which I also add.
There is no hook called useForm
in formik api, I think you're mixing it with useFormik
hook.
formik-material-ui
is using useField
hook internally so you don't have to wrap your component with formik's Field
component, instead you can directly render your MyCheckbox
like:
<MyCheckbox name="sectionChoices" value={label} label={label} />