Skip to content

Instantly share code, notes, and snippets.

@emartini
Created January 24, 2018 15:55
Show Gist options
  • Save emartini/407d498782c3fdc51e30c52ef6a31a6b to your computer and use it in GitHub Desktop.
Save emartini/407d498782c3fdc51e30c52ef6a31a6b to your computer and use it in GitHub Desktop.
formik
import * as React from 'react';
import {
withFormik,
FormikProps,
FormikErrors,
FieldProps,
Form,
Field
} from 'formik';
interface Props {
message?: string;
initialValues: FormValues;
}
interface FormValues {
email: string;
password: string;
}
const PasswordField: React.SFC<
FieldProps<FormValues> & React.InputHTMLAttributes<{}>
> = props => {
const { field, form, ...inputProps } = props;
const { name } = field;
console.log(props);
const isFieldTouch: boolean = (form.touched as any)[name];
const fieldErrors: FormikErrors<FormValues> = (form.errors as any)[name];
return (
<>
<input type="password" {...inputProps} {...field} />
{isFieldTouch && fieldErrors && fieldErrors}
</>
);
};
const QuoteForm: React.SFC<{}> = (props: Props & FormikProps<FormValues>) => {
const { touched, errors, isSubmitting, message } = props;
console.log(props);
return (
<Form>
<div>
<label htmlFor="email">email</label>
<br />
<Field type="email" name="email" id="email" />
{touched.email && errors.email && <div>{errors.email}</div>}
</div>
<div>
<label htmlFor="pswrd">Password</label>
<br />
<Field
name="password"
component={PasswordField}
id={'pswrd'}
placeholder="password"
/>
</div>
<div>...</div>
<button type="submit" disabled={isSubmitting}>
Submit
</button>
</Form>
);
};
const FormikQuote = withFormik<Props, FormValues>({
mapPropsToValues: props => {
return {
email: props.initialValues.email || '',
password: props.initialValues.password || ''
};
},
validate: (values: FormValues) => {
const errors = {} as FormikErrors<FormValues>;
if (values.password !== '123') errors.password = 'invalid';
return errors;
},
handleSubmit: (values, { setSubmitting }) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
setSubmitting(false);
}, 2000);
}
})(QuoteForm);
export default () => (
<FormikQuote
initialValues={{
email: 'esteban@google.com',
password: ''
}}
/>
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment