-
-
Save felipecodes/d1790af05b1d1877bb3848c1728fda9e to your computer and use it in GitHub Desktop.
Formik async email signup input
This file contains 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 debounce from 'utils/debounce'; | |
class EmailInput extends React.Component { | |
checkEmail = value => { | |
// only check if the field passes Yup email validation first | |
if ( | |
!this.props.form.errors[this.props.name].includes( | |
'invalid' /* or whatever your error message is*/ | |
) | |
) { | |
MyApi.checkEmail(value).then( | |
success => { | |
this.props.form.setFieldError(this.props.name, undefined); | |
// if you need to show more info, like a checkbox: | |
// this.props.form.setStatus({ email: true }) | |
}, | |
error => | |
this.props.form.setFieldError( | |
this.props.name, | |
transformErrorToEnglish(error) | |
) | |
); | |
} | |
}; | |
debouncedCheckEmail = debounce(this.checkEmail, 300); // 300ms debounce | |
handleChange = e => { | |
this.props.field.handleChange(e); // this will let Formik's default validation take place | |
this.debouncedCheckEmail(e.target.value); | |
}; | |
handleBlur = e => { | |
this.props.field.handleBlur(e); // this will let Formik's default validation take place | |
this.checkEmail(e.target.value); | |
}; | |
render() { | |
const { field, form, ...props /* like placeholder */ } = this.props; | |
return ( | |
<div> | |
<input | |
{...field} | |
{...props} | |
onChange={this.handleChange} | |
onBlur={this.handleBlur} | |
/> | |
{/** show errors */} | |
</div> | |
); | |
} | |
} | |
export default EmailInput | |
// Usage | |
<Field name="email" component={EmailInput} placeholder="jane@apple.com" /> | |
// or | |
<Field name="email" render={props => <EmailInput {...props} {...otherPropsYouMightNeed} />} /> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment