Created
November 20, 2017 19:59
-
-
Save itsMapleLeaf/7cace0f2ca21fc7ee302a1520788a96b to your computer and use it in GitHub Desktop.
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 Yup from 'yup' | |
import { withFormik, FormikProps, FormikErrors } from 'formik' | |
interface FormValues { | |
email: string | |
password: string | |
} | |
const InnerForm = (props: FormikProps<FormValues>) => ( | |
<form onSubmit={props.handleSubmit}> | |
<input | |
type="email" | |
name="email" | |
onChange={props.handleChange} | |
onBlur={props.handleBlur} | |
value={props.values.email} | |
/> | |
{props.touched.email && | |
props.errors.email && <div>{props.errors.email}</div>} | |
<input | |
type="password" | |
name="password" | |
onChange={props.handleChange} | |
onBlur={props.handleBlur} | |
value={props.values.password} | |
/> | |
{props.touched.password && | |
props.errors.password && <div>{props.errors.password}</div>} | |
<button type="submit" disabled={props.isSubmitting}> | |
Submit | |
</button> | |
</form> | |
) | |
const MyForm = withFormik<FormikProps<FormValues>, FormValues>({ | |
mapPropsToValues: props => ({ email: '', password: '' }), | |
validate: (values, props) => { | |
let errors = {} as FormikErrors | |
if (!values.email) { | |
errors.email = 'Required' | |
} else if ( | |
!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email) | |
) { | |
errors.email = 'Invalid email address' | |
} | |
return errors | |
}, | |
handleSubmit: ( | |
values, | |
{ | |
props, | |
setSubmitting, | |
setErrors /* setValues, setStatus, and other goodies */, | |
}, | |
) => { | |
// do submitting things | |
}, | |
})(InnerForm) | |
const Basic = () => ( | |
<div> | |
<h1>My Form</h1> | |
<p>This can be anywhere in your application</p> | |
<MyForm /> {/* <-- errors here */} | |
</div> | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment