'How to use material UI Checkbox with formik?
I am not able to code in the right way such that formik.values will reflect into Material UI's Checkbox
Solution 1:[1]
Use the as prop with Formik Field and pass any props required to the Field itself. It will pass them onto FormControlLabel. For example, here the label field is passed down to FormControlLabel:
<Formik>
<Form>
<Field
as={FormControlLabel}
type="checkbox"
name="myFormikName"
control={<Checkbox />}
label="Text on screen"
/>
</Form>
</Formik>
If you have multiple checkboxes with the same name (array) you need to pass the "checked" value like so. Checks if the Formik 'name' array includes the name.
const { values } = useFormikContext()
render (
{names?.map(name => (
<Field
type="checkbox"
name="names"
value={name.fullName}
key={name.id}
as={FormControlLabel}
control={
<Checkbox
checked={values.names.includes(name.fullName)}
/>
}
label={name.fullName}
/>
))}
)
Solution 2:[2]
Checkboxes are a little tricky to include in third party forms packages, and Material UI doesn't help with that either.
What you need to do is use the FormControlLabel component to handle the onChangge event that formik needs. Then on the Checkbox you just set the checked prop to be whatever formik has in its values.
Here is an example I use for a Checkbox to set an isAdmin value.
const formik = useFormik({
initialValues:{
isAdmin: false
},
});
<FormControlLabel
control={<Checkbox checked={formik.values.isAdmin} />}
label="is Admin"
name="isAdmin"
onChange={formik.handleChange}
/>
Solution 3:[3]
<FormControlLabel control={<Checkbox defaultChecked />} label="Label" name="checkbox" onChange={props.handleChange} />
you just need to put it in your form like this :
<Formik
initialValues={{ checkbox:true }}
onSubmit={(values, actions) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
actions.setSubmitting(false);
}, 1000);
}}
>
{props => (
<form onSubmit={props.handleSubmit}>
<FormControlLabel control={<Checkbox defaultChecked />} label="Label" name="checkbox" onChange={props.handleChange} />
{props.errors.name && <div id="feedback">{props.errors.name}</div>}
<button type="submit">Submit</button>
</form>
)}
</Formik>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Richard Hpa |
| Solution 3 | Samira |
