Last active
February 21, 2024 14:02
-
-
Save dcortesnet/55bde6521d1e2875e364e03ce2ba90ca to your computer and use it in GitHub Desktop.
React formik example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React from 'react'; | |
| import { Formik } from 'formik'; | |
| const Basic = () => ( | |
| <div> | |
| <h1>Anywhere in your app!</h1> | |
| <Formik | |
| initialValues={{ email: '', password: '' }} | |
| validate={values => { | |
| const errors = {}; | |
| if (!values.email) { | |
| errors.email = 'Required'; | |
| } else if ( | |
| !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(values.email) | |
| ) { | |
| errors.email = 'Invalid email address'; | |
| } | |
| return errors; | |
| }} | |
| onSubmit={(values, { setSubmitting }) => { | |
| setTimeout(() => { | |
| alert(JSON.stringify(values, null, 2)); | |
| setSubmitting(false); | |
| }, 400); | |
| }} | |
| > | |
| {({ | |
| values, | |
| errors, | |
| touched, | |
| handleChange, | |
| handleBlur, | |
| handleSubmit, | |
| isSubmitting, | |
| /* and other goodies */ | |
| }) => ( | |
| <form onSubmit={handleSubmit}> | |
| <input | |
| type="email" | |
| name="email" | |
| onChange={handleChange} | |
| onBlur={handleBlur} | |
| value={values.email} | |
| /> | |
| {errors.email && touched.email && errors.email} | |
| <input | |
| type="password" | |
| name="password" | |
| onChange={handleChange} | |
| onBlur={handleBlur} | |
| value={values.password} | |
| /> | |
| {errors.password && touched.password && errors.password} | |
| <button type="submit" disabled={isSubmitting}> | |
| Submit | |
| </button> | |
| </form> | |
| )} | |
| </Formik> | |
| </div> | |
| ); | |
| export default Basic; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment