Formik For React: Introduction to Form Management Done Right

Breaking down the Formik React Package to make form management simple

Pre-Reading

Form Elements in React

Yup: Object parsing and validation

Installing and Importing Formik

npm i formik
import { Formik, FormikProps, Form, Field } from 'formik';

Structuring a Formik Form

...
import { Formik, FormikProps, Form, Field } from 'formik';

export class MyForm extends React.Component {
handleSubmit = (values, {
props = this.props,
setSubmitting
}) => {

//process form submission here
//done submitting, set submitting to false
setSubmitting(false);
return;
}
render() {

return(
<Formik
initialValues={{
first_name: '',
email: '',
gender: ''
}}
validate={(values) => {
let errors = {};

//check if my values have errors
return errors;
}}
onSubmit={handleSubmit}
render={formProps: FormikProps => {
return(
<Form>
<Field ... />
<Field ... />
<Field ... />
<button
type="submit"
disabled={formProps.isSubmitting}>
Submit Form
</button>
</Form>
);
}
/>);
}
}

Configuring a Formik <Field />

<Field 
type="text"
name="email"
placeholder="Email Address"
className='textbox'
/>

{ formProps.touched.email &&
formProps.errors.email &&
<span className='error'>{formProps.errors.email}</span>
}

The <ErrorMessage /> Object

{ formProps.touched.email &&
formProps.errors.email &&
<span className='error'>{formProps.errors.email}</span>
}
<ErrorMessage name="email" />

Configuring Validation

<Formik 
validate
={(values) => {
let errors = {};

//check if my values have errors
return errors;
}}
...
/>
<Formik
validate
={(values) => {
let errors = {};
if(!values.email || is_valid_email(values.email))
errors.email = 'Valid Email Address Required';

return errors;
}}
...
/>
//define my schema using Yup
const formSchema = yup.object().shape({
...
});
<Formik
validationSchema={formSchema}

...
/>

Abstracting your handlers

import * as myForm from './forms/myForm';export class MyForm extends React.Component {  render() {

return(
<Formik
initialValues={myForm.initialValues}
validate={myForm.validate}
onSubmit={myForm.onSubmit}
render={
(formProps: FormikProps) => {

<Form>
<Field ... />
...
</Form>
}}
/>
);
}
}

Using Other Input types with Field

<Field
name="gender"
component="select"
placeholder="Your Gender">
<option value="male">Male</option>
<option value="female">Female</option>
</Field>

A Note on FieldArrays

Summing Up

Programmer and Author. Director @ JKRBInvestments.com. Creator of LearnChineseGrammar.com for iOS.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store