Skip to content

Instantly share code, notes, and snippets.

@felipecodes
Forked from jaredpalmer/EmailInput.jsx
Created December 2, 2017 01:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save felipecodes/d1790af05b1d1877bb3848c1728fda9e to your computer and use it in GitHub Desktop.
Save felipecodes/d1790af05b1d1877bb3848c1728fda9e to your computer and use it in GitHub Desktop.
Formik async email signup input
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