Skip to content

Instantly share code, notes, and snippets.

@AlexGeb
Created October 1, 2018 08:47
Show Gist options
  • Save AlexGeb/c5345ce55a21c29e90f2d795a13c9c58 to your computer and use it in GitHub Desktop.
Save AlexGeb/c5345ce55a21c29e90f2d795a13c9c58 to your computer and use it in GitHub Desktop.
List of Formik forms :
import React, { Component } from "react";
import { Formik, FastField, ErrorMessage } from "formik";
import * as Yup from "yup";
const schemaForm1 = Yup.object().shape({
email: Yup.string()
.email("Invalid email")
.required("Required"),
password: Yup.string()
.min(2, "Too Short!")
.max(50, "Too Long!")
.required("Required")
});
class App extends Component {
constructor(props) {
super(props);
this.formikRefs = { form1: React.createRef(), form2: React.createRef() };
this.initialValues = {
email: "",
password: "",
address: "",
country: ""
};
this.newValues = this.initialValues;
}
getFormsFromRefs = () =>
Object.keys(this.formikRefs).map(
formikRefName => this.formikRefs[formikRefName].current
);
submitAllForms = () => {
const submitingPromises = this.getFormsFromRefs().map(
form => (console.log(form), form.submitForm())
);
Promise.all(submitingPromises).then(() => {
this.resetAllForms();
console.log("submitted values : ", this.newValues);
});
};
resetAllForms = () => {
console.log("reset");
this.getFormsFromRefs().map(form => form.resetForm());
};
handleSubmit = (values, actions) => {
this.newValues = { ...this.newValues, ...values };
};
render() {
const { email, password, address, country } = this.initialValues;
console.log("rendering");
return (
<div>
<h1>Formik demo</h1>
<h2>Table of forms</h2>
<TableForm />
<h2>List of forms</h2>
<div>
<ul>
<li>
<Formik
ref={this.formikRefs.form1}
initialValues={{ email, password }}
onSubmit={this.handleSubmit}
validationSchema={schemaForm1}
>
<div>
<FastField name="email" placeholder="email" />
<ErrorMessage name="email" />
<FastField name="password" placeholder="password" />
<ErrorMessage name="password" />
</div>
</Formik>
</li>
<li>
<Formik
ref={this.formikRefs.form2}
initialValues={{ address, country }}
onSubmit={this.handleSubmit}
>
<div>
<FastField name="address" placeholder="address" />
<FastField name="country" placeholder="country" />
</div>
</Formik>
</li>
</ul>
<button type="submit" onClick={this.submitAllForms}>
Submit
</button>
<button onClick={this.resetAllForms}>Reset</button>
</div>
</div>
);
}
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment