Search code examples
reactjsmaterial-uiformik

How to initialize dynamic MUI Checkboxes in Formik React form?


So... I'm writing a form with Formik and MUI that deals with product's images; each product has different element in which a collection of images and each image has an id, a path and a boolean:

product: { ...,  images: { id , path , isMain } }

As I am using the same form to create and update a product, I pass a prop { product } that can be null... So I am initializing my value like this:

<Formik
    initialValues={{
      name: product && product.name ? product.name : "",
      description: product && product.description ? product.description : "",
      price: product && product.price ? product.price : "",
      quantityInStock: product && product.quantityInStock ? product.quantityInStock : "",
      images: product && product.images ? product.images : []
    }}
    onSubmit={(values) => {
      console.log(values);
    }}
    enableReinitialize={true}
  >

Question 1 : Is this the right way ???

Question 2 (the one I am really struggeling with...) : I am rendering each image with a checkbox (for the boolean isMain) Only one checkbox should be selected for the collection of images. So far, I do have the checkbox and the value is updated in the Formik's values BUT... I do have this error when i click on the checkbox : "MUI: A component is changing the default checked state of an uncontrolled SwitchBase after being initialized. To suppress this warning opt to use a controlled SwitchBase."

Here is what I'm doing:

{values.images.map((image, index) => {
   const name = `images[${index}].isMain`
   return (
     <div key={index}>
       <Image  src={image.path} alt={"image"} fluid/>
       <Checkbox 
         name={name}
         defaultChecked={values.images[index].isMain}
         onChange={handleChange}
       />
     </div>
   );
  })}

If i change defaultChecked to checked, the checkbox stays in his original state (checked or not) but the value is still updated...

Any idea on how to init the value of these checkboxes and get rid of this error would be greatly appreciated !!!

(bonus: if you have a hint on how to group the checboxes, I'll take that too !)

Thanks...


Solution

  • Please use checked props.

    <Checkbox 
             name={name}
             checked={values.images[index].isMain}
             onChange={handleChange}
    />