@mui/material <Checkbox> with Formik

Viewed 556

I wish to build a React (multi step) form using Formik and Mui. I cannot understand how to bind/control the mui checkbox element


import { Button, Checkbox, Typography } from "@mui/material";
import { Field, Form, Formik } from "formik";
import "./styles.css";

export default function App() {
  var fruitValues = ["apple", "banana"];
  function handleSubmit(values, actions) {
    fruitValues = values.fruit;
    console.debug(values.fruit);
  }

  return (
    <div className="App">
      <Formik initialValues={{ fruit: ["apple"] }} onSubmit={handleSubmit}>
        <Form id="test2">
          <Checkbox name="fruit" value="apple" label="Apple" />
          <Checkbox name="fruit" value="banana" label="Banana" />
          <Checkbox name="fruit" value="orange" label="Orange" />
          <Button type="submit">Submit</Button>
        </Form>
      </Formik>
    </div>
  );
}

See https://codesandbox.io/s/thirsty-wing-91glso?file=/src/App.js:0-1380

2 Answers

I am working on this as well. Seems like something that should be covered in the docs but just isn't.

There is this example. It covers doing something like this ...

<Form>
  <Field
    type="email"
    name="email"
    component={TextField}
    color={"error"}
  />

But there isn't any explanation of where this comes from or what is happening here.

My reaction is a little late but I faced the same issue and made it work as follow.

import React from 'react'
import { Field, Form, Formik } from 'formik'
import Checkbox from '@mui/material/Checkbox'
import FormControlLabel from '@mui/material/FormControlLabel'

export default function Example() {
  return (
    <Formik>
      <Form>
        <Field name="terms_of_condition">
          {({ field }) => (
            <FormControlLabel
              onChange={field.onChange}
              control={<Checkbox name="terms_of_condition" />}
              label="Terms of conditions"
              sx={sx}
              value="on"
            />
          )}
        </Field>
      </Form>
    </Formik>
  )
}
Related