<FieldArray/> component of Formik Library is used for managing a list of form fields (mostly in forms).
In cases like when we don’t exactly know how many fields will there be required (as in a todo app, we can’t know how many tasks user will put into), we use <FieldArray/> component.
We use this component inside <Formik> and <Form> tags that also come from formik library.
To use this import {FieldArray, Form, Formik} from formik and do as follow.
import { Form, Formik, FieldArray } from "formik";
export const TodoApp = () => (
<Formik initialValues={{ todos: [] }}>
<Form>
{/* Pass name of the array, i.e. `todos` */}
<FieldArray name="todos">
{({ form, ...fieldArrayHelpers }) => {
const onAddClick = () => {
fieldArrayHelpers.push({
id: values.todos.length,
content: "",
isCompleted: false
});
};
return (
<React.Fragment>
<button onClick={onAddClick}>Add Item</button>
{form.values.todos.map(({ id }, index) => (
<TodoItem key={id} index={index} />
))}
</React.Fragment>
);
}}
</FieldArray>
</Form>
</Formik>
);