Skip to content

Instantly share code, notes, and snippets.

@deshanm
Created May 4, 2020 22:52
Show Gist options
  • Select an option

  • Save deshanm/f1fa0f93f1f6d5bbfd77e2a3e27f9384 to your computer and use it in GitHub Desktop.

Select an option

Save deshanm/f1fa0f93f1f6d5bbfd77e2a3e27f9384 to your computer and use it in GitHub Desktop.
Yup Formik Dynamic Array of Objects
import "./styles.css";
import * as Yup from "yup";
import { ErrorMessage, Field, FieldArray, Form, Formik } from "formik";
import React from "react";
const App = () => (
<div>
<h3>Organzation Form (Dyanamic users - Array of Object) </h3>
<hr />
<Formik
initialValues={{
users: [{
name: "deshan madurajith",
email: "[email protected]"
},
{
name: "Hello Desh",
email: "[email protected]"
}
],
organizationName: []
}}
validationSchema={Yup.object({
organizationName: Yup.string().required(
"Organization Name is required"
),
users: Yup.array().of(
Yup.object().shape({
name: Yup.string().required("Name required"),
email: Yup.string()
.required("email required")
.email("Enter valid email")
})
)
})}
onSubmit={values => alert(JSON.stringify(values, null, 2))}
render={({ values }) => (
<Form>
<h5>Form </h5>
<Field placeholder="Organization name" name={`organizationName`} />
<ErrorMessage name={`organizationName`} />
<h5>Organzation users </h5>
<FieldArray
name="users"
render={arrayHelpers => {
const users = values.users;
return (
<div>
{users && users.length > 0
? users.map((user, index) => (
<div key={index}>
<Field
placeholder="user name"
name={`users.${index}.name`}
/>
<ErrorMessage name={`users.${index}.name`} />
<br />
<Field
placeholder="user email"
name={`users.${index}.email`}
/>
<ErrorMessage name={`users.${index}.email`} />
<br />
<button
type="button"
onClick={() => arrayHelpers.remove(index)} // remove a friend from the list
>
-
</button>
<br />
<br />
</div>
))
: null}
<button
type="button"
onClick={() =>
arrayHelpers.push({
name: "",
email: ""
})
} // insert an empty string at a position
>
add a User
</button>
<br />
<br />
<br />
<div>
<button type="submit">Form Submit</button>
</div>
</div>
);
}}
/>
<hr />
</Form>
)}
/>
</div>
);
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment