Better forms with React
An average form
Enter Formik!
import React, { Component } from 'react';
import { withFormik } from 'formik';
import * as Yup from 'yup';
const UserForm = props => {
const {
values,
touched,
errors,
dirty,
isSubmitting,
handleChange,
setFieldValue,
handleBlur,
handleSubmit,
handleReset
} = props;
return (
<form className='p-5' onSubmit={handleSubmit} >
<div className="form-group">
<label>
Imaginary Email
</label>
<input
name="email"
type="text"
className={`form-control ${errors.email && touched.email && 'is-invalid'}`}
value={values.email}
onChange={handleChange}
onBlur={handleBlur} />
{
errors.email &&
touched.email &&
<div className='invalid-feedback'>
{errors.email}
</div>
}
</div>
<button type='submit' className='btn btn-outline-primary' disabled={isSubmitting}>
{isSubmitting ? 'Working. Please Wait...' : 'Click Me!'}
</button>
</form >
);
}
export default withFormik({
mapPropsToValues: props => ({
email: props.user.email
}),
validationSchema: Yup.object().shape({
email: Yup.string().email('Invalid email address!').required('Email is required!')
}),
handleSubmit: (values, { setSubmitting }) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
setSubmitting(false);
}, 1000);
}
})(UserForm);
Quick Demo
Better forms with React
By Rohan Bagchi
Better forms with React
- 621