DEV Community

Momen Hesham
Momen Hesham

Posted on

Nested Array Inside Formik

I am trying to write a nested array of items inside Formik, with the Field I am okay but with the ImageField it's a component I wrote for uploading images, I need to give it a key of the array like the field but I tried many solutions none of them is working, any help with this?

                          else if (data.type === "items") {
                            console.log(formikBag);
                            const dataKey = data.key + suffix;
                            return (
                              <>
                                <FieldArray name={dataKey}>
                                  <React.Fragment>

                                    {data.items &&
                                      data.items.length > 0 &&
                                      data.items.map((item, index) => {
                                        // tslint:disable-next-line: no-shadowed-variable
                                        const { key, title } = item;
                                        if (item.type === "text") {
                                          return (
                                            <Field
                                              name={`${dataKey}[${index}].${key}`}
                                              component={TextField}
                                              margin="normal"
                                              variant="outlined"
                                              placeholder={title}
                                              required={true}
                                              label={title}

                                            />
                                          )
                                        }
                                        else if (item.type === "image") {
                                          return (
                                            <ImageField
                                              value={(formikBag.values as any)[data.key]}
                                              error={(formikBag.errors as any)[data.key]}
                                              setValue={value =>
                                                formikBag.setFieldValue(data.key as string, value)
                                              }
                                            />
                                          )
                                        }
                                      })}

                                  </React.Fragment>
                                </FieldArray>

                              </>
                            )
                          }

Top comments (0)