Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.


1 Answers

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

like image 92
DavidP Avatar answered Aug 17 '26 16:08

DavidP



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!