Formik for form handling in React.js


Purpose of formic is to remove the complexity of form handling in react and make form submission simpler.

Formic uses yup to validate the form fields which is very simple to use

First install the formic library

npm install –save formic

Example

import React, { Component} from 'react';
import { Formik, FormikProps, Form, Field, ErrorMessage } from 'formik';
export class FormExample extends Component {
   handleSubmit = (values, {
      props = this.props,
      setSubmitting
   }) => {
      setSubmitting(false);
      return;
   }  
   render() {
      return(
         <Formik
            initialValues={{
               first_name: '',
               last_name: ''
            }}
            validate={(values) => {
               let errors = {};  
               if(!values.first_name)
               errors.first_name = "first name Required";
               //check if my values have errors
               return errors;
            }
         }
         onSubmit={this.handleSubmit}
         render={formProps => {
            return(
               <Form>
                  <Field type="text" name="first_name" placeholder="First Name"/>
                  <ErrorMessage name="first_name" />
                  <Field type="text" name="last_name" placeholder="Last Name" />
                  <ErrorMessage name="last_name" />
                  <button type="submit" disabled={formProps.isSubmitting}>
                     Submit Form
                  </button>
               </Form>
            );
         }}
      />);
   }
}

The code is very self explanatory. We have two fields first_name and last_name. we are validating the first_name field and displaying error message if it's empty.

Note the imported components from formic → Formik, FormikProps, Form, Field, ErrorMessage

We can use yup which has good support with formik library

const validationSchema = Yup.object({
   first_name: Yup.string("Enter a First Name")
   .required("First Name is required"),
   last_name: Yup.string("Enter your Last Name")
   .last_name("Enter a valid Last Name")
   .required("Last Name is required")
})

We can validation like above using yup and add the validations Schema on formik component to make it work.

<Formik
   initialValues={values}
validationSchema={validationSchema}
/>

Updated on: 04-Sep-2019

257 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements