简体   繁体   中英

Dynamically add fields to Formik form

I need a way to add fields to a Formik form in a for loop. I've read the documentation for the FieldArray component, but I don't really understand how to use it. This is my current code:

function generate(values) {
        for (let i = 0; i < 10; i++) {
            values.test.push({
                hello: "world"
            })
        }
    }

    return (
        <div>
            <Formik initialValues={{test: []}}/>
            {(values)=>(
                <Form>
                    <FieldArray>
                        {()=>generate(values)}
                        <p>{JSON.stringify(values)}</p>
                    </FieldArray>
                </Form>
            )}
        </div>
    )

At the moment, it just shows an empty page. Not even an error message.

The reason your code above is not working is because you are invoking the field array and form outside of <Formik />

It should be:

<Formik render={({ values }) => (
  <Form>
    <FieldArray />
  </Form>
)/>

And not:

<Formik initialValues={{test: []}} />
<Form>
  <FieldArray />
</Form>

You can see a clearer example here: https://codesandbox.io/s/1o8n593z6q

You can just use setValues to dynamically add or remove fields form formik.

Here's a code sample it might help

      <Formik initialValues={{} as Record<string, any>} onSubmit={() => {}}>
    {({values, setValues}) => (
      <Form>
        {customers.map(e => (
          <Component
            name={e.firstName}
            customerId={e.customerId}
            onClick={() => {
              // @ts-ignore
              if (values?.[e.customerId])
                setValues(prev => _.omit(prev, e.customerId));
              else {
                setValues({...values, [e.customerId]: e});
              }
            }}
            // @ts-ignore
            isSelected={values?.[e.customerId]}
          />
        ))}

        {Object.values(values).map(v => (
          <h5 style={{color: 'red'}}>{v.firstName}</h5>
        ))}
      </Form>
    )}
  </Formik>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM