最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Dynamically add fields to Formik form - Stack Overflow

programmeradmin8浏览0评论

I need a way to add fields to a Formik form in a for loop. I've read the documentation for the FieldArray ponent, 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.

I need a way to add fields to a Formik form in a for loop. I've read the documentation for the FieldArray ponent, 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.

Share Improve this question asked Jan 23, 2021 at 4:24 user14625847user14625847 1
  • Hi there, when you say add dynamic fields, can you provide more update on what kind of fields are you looking to add? Input text+label or checkbox? Would be good to know the real use case. – Nagaraj Tantri Commented Jan 24, 2021 at 2:29
Add a ment  | 

2 Answers 2

Reset to default 1

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>
发布评论

评论列表(0)

  1. 暂无评论