Replies: 1 comment
-
|
import { Formik, Form, Field, FieldArray, ErrorMessage } from 'formik';
function MyForm() {
return (
<Formik
initialValues={{ selects: [{ value: '' }] }} // start with one select
onSubmit={(values) => console.log(values)}
>
{({ values }) => (
<Form>
<FieldArray name="selects">
{(arrayHelpers) => (
<div>
{values.selects.map((select, index) => (
<div key={index}>
<Field as="select" name={`selects.${index}.value`}>
<option value="">Choose...</option>
<option value="a">Option A</option>
<option value="b">Option B</option>
</Field>
{/* Remove button — only show if more than one */}
{values.selects.length > 1 && (
<button type="button" onClick={() => arrayHelpers.remove(index)}>
Remove
</button>
)}
</div>
))}
{/* THIS is the button to add another select */}
<button
type="button"
onClick={() => arrayHelpers.push({ value: '' })}
>
Add another
</button>
</div>
)}
</FieldArray>
<button type="submit">Submit</button>
</Form>
)}
</Formik>
);
}Key points:
The |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I have a
Selectcomponent and under it there's a button to basically create another one. I have researched ways of doing this, but I haven't found anything concise.I read that
FieldArraymight help, and I'm trying to understand the example provided in the documentation. But it doesn't solves my problem:Beta Was this translation helpful? Give feedback.
All reactions