How to crate basic form in React using Formik

How to crate basic form in React using Formik

ReactJS 15-03-2023 Saheb Sutradhar

React Formik

 

Formik is a library helps to handle form in React , Formik helps to handle Form submission , From Validation , Manages Form data.

Installation

npm install formik

 

Formik library provides a hook called useFormik() which helps to manage our form by providing three features 

1. Manage form data

2. Form Validation

3. Form Submission 

 

Full Code : 

import { useFormik } from 'formik';


const formikForm = ()=>{

  const validation = (values) => {
    let error = {};
    if (!values.name) {
      error.name = 'Name is required';
    }
    if (!values.phone) {
      error.phone = 'Phone is required';
    }
    if (!values.address) {
      error.address = 'Address is required';
    }

    return error;
  }


const formik = useFormik({
  initialValues: {
    name: '',
    phone: '',
    address: ''
  },
  validate: validation,
  onSubmit: (values) => {
    console.log(values)
    console.log(formik)
  }
})







  return (
    <form onSubmit={formik.handleSubmit}>
    <div>
      <input type="text" placeholder='Name' name='name' onChange={formik.handleChange} value={formik.values.name} onBlur={formik.handleBlur} />
      {
        formik.touched.name && formik.errors.name ?
          <p style={{ color: 'red' }}>{formik.errors.name}-Name</p>
          :
          null
      }

    </div>

    <div>
      <input type="text" placeholder='Phone' name='phone' onChange={formik.handleChange} value={formik.values.phone} onBlur={formik.handleBlur} />
      {
        formik.touched.phone && formik.errors.phone ?
          <p style={{ color: 'red' }}>{formik.errors.phone} - Phone</p>
          :
          null
      }

    </div>
    <div>
      <input type="text" placeholder='Address' name='address' onChange={formik.handleChange} value={formik.values.address} onBlur={formik.handleBlur} />
      {
        formik.touched.address && formik.errors.address ?
          <p style={{ color: 'red' }}>{formik.errors.address}-Address</p>
          :
          null
      }

    </div>
    <button type='submit'>Submit</button>
  </form>
  )
}

export default formikForm;

 

In the above code 

Step 1

Import the useFormik() hook

import { useFormik } from 'formik';

Step 2

Configure the form state , submit and validation

  const validation = (values) => {
    let error = {};
    if (!values.name) {
      error.name = 'Name is required';
    }
    if (!values.phone) {
      error.phone = 'Phone is required';
    }
    if (!values.address) {
      error.address = 'Address is required';
    }

    return error;
  }


const formik = useFormik({
  initialValues: {
    name: '',
    phone: '',
    address: ''
  },
  validate: validation,
  onSubmit: (values) => {
    console.log(values)
    console.log(formik)
  }
})

Step 3

Create the form

 <form onSubmit={formik.handleSubmit}>
      <div>
        <input type="text" name='name' onChange={formik.handleChange} value={formik.values.name} onBlur={formik.handleBlur} />
        {
          formik.touched.name && formik.errors.name ?
            <p style={{ color: 'red' }}>{formik.errors.name}</p>
            :
            null
        }

      </div>

      <div>
        <input type="text" name='phone' onChange={formik.handleChange} value={formik.values.phone} onBlur={formik.handleBlur} />
        {
          formik.touched.phone && formik.errors.phone ?
            <p style={{ color: 'red' }}>{formik.errors.phone}</p>
            :
            null
        }

      </div>
      <div>
        <input type="text" name='address' onChange={formik.handleChange} value={formik.values.address} onBlur={formik.handleBlur} />
        {
          formik.touched.address && formik.errors.address ?
            <p style={{ color: 'red' }}>{formik.errors.address}</p>
            :
            null
        }

      </div>
      <button type='submit'>Submit</button>
    </form>

 

 

NOTE :  In the field name attribute value and the  initialValues property name should be same . 

 

onChange={formik.handleChange}  - handleChange automatically updated the value to the form state when it changes 
 
value={formik.values.address} - formik.values.address helps to get access the form state value 
 
onBlur={formik.handleBlur} -  handleBlur sets flag is the particular field is touched or not 
 
 
Now the time to submit the form and get the form data
 
For that add a button with type = 'submit'  <button type='submit'>Submit</button> and in the form opening tag  add <form onSubmit={formik.handleSubmit}>    , so when we submit the form  the function will get fired which is added as a value of 
onSubmit in the useFormik configuration
 
 
 

Validation : 

To show the validation error message we have added below code clock

        {
          formik.touched.name && formik.errors.name ?
            <p style={{ color: 'red' }}>{formik.errors.name}</p>
            :
            null
        }
 
which checks if the name property was focused and user did not enter any value 
 
 

getFieldProps()

getFieldProps() takes care of  onChange={formik.handleChange} value={formik.values.name} onBlur={formik.handleBlur}

The same code you can write with out getFiledProps()

<input type="text" placeholder='Name' name='name' onChange={formik.handleChange} value={formik.values.name} onBlur={formik.handleBlur} />

The same code you can write with getFieldProps()

<input type="text" placeholder='Name' name='name'  {...formik.getFiledProps('name')} />
 

This article will help you to create and understand how to create basic formik form in react

 
 
 

 

 

Related Posts

Card image cap

ReactJS Tutorial

ReactJS 07-09-2022 Saheb Sutradhar

ReactJS Tutorial Basic ...

Card image cap

React cteateContext and useContect context hook

ReactJS 21-12-2022 Saheb Sutradhar

React context hook ...

Card image cap

Formik Components

ReactJS 17-03-2023 Saheb Sutradhar

Formik Components , how to create from using formik components ...

Card image cap

How to disabled the submit button in formik

ReactJS 17-03-2023 Saheb Sutradhar

How to disabled the submit button in formik ...

Card image cap

How to load initial value in formik form

ReactJS 17-03-2023 Saheb Sutradhar

How to load initial value in formik form ? ...