Formik Components

Formik Components

ReactJS 17-03-2023 Saheb Sutradhar

Formik Components

 

A few Components offered by Formik can be used to speed up our development, those components help us to reduce code duplication , and write the code in a Organized way.

Let's learn formik componets by creating simple registration form 

 

Step 1.

Import all  Form, Formik , Field ,ErrorMessage , FieldArray components form formik library make sure the formik library is installed in your application if no then run npm install formik to install the package from the root directory of your application.

import { Form, Formik , Field ,ErrorMessage , FieldArray} from 'formik';

Step 2.

Create a form using Form and Filed components not using <form> and <input> html element .

<Form>


<div>
  <Field  name='name'>
        {(props)=>{
          const {meta , field} = props;
           /* 
           this field object is having all the properties of a field eg. onChange , type , name , value , onBlur
            and meta object is having all the properties error, initialError, initialTouched, initialValue, touched, value
          */
             return (
                  <>
                    <input {...field} placeholder="Enter Name"/>
                 </>
             )
        }}
      </Field>
</div>

<div>
  <Field  name='password'>
        {(props)=>{
          const {meta , field} = props;
             return (
                  <>
                    <input type='password' {...field} placeholder="Enter password"/>
                 </>
             )
        }}
      </Field>
</div>

<div>
    <FieldArray name='skills'>
        {(filedArrayObj)=>{
          const {form , remove , push} = filedArrayObj;
          const {values}=form;
          const {skills} = values;
          return (
            <div>
              <button onClick={(event)=>{event.preventDefault();push('')}}>Add</button> 
               {
                 skills.map((skill , index)=>{
                   return <div key={index}>
                      <Field type="text" placeholder='Skill' name={`skills[${index}]`}  validate={validateSkills} />
                      {index>0?<button onClick={()=>{remove(index)}}>Remove</button>:null}
                   </div>
                 })
              } 
            </div>
          )
        }}
      </FieldArray>
</div>

</Form>

 

FieldArray component Helps to work with array data in form.

<FieldArray name='skills'>
        {(filedArrayObj)=>{
          const {form , remove , push} = filedArrayObj;
          const {values}=form;
          const {skills} = values;
          return (
            <div>
              <button onClick={(event)=>{event.preventDefault();push('')}}>Add</button> 
               {
                 skills.map((skill , index)=>{
                   return <div key={index}>
                      <Field type="text" placeholder='Skill' name={`skills[${index}]`}  validate={validateSkills} />
                      {index>0?<button onClick={()=>{remove(index)}}>Remove</button>:null}
                   </div>
                 })
              } 
            </div>
          )
        }}
      </FieldArray>

In the FiledArray function returns filedArrayObj you can use any name , the filedArrayObj object has form , remove , push

  • remove() helps to remove array element by passing the index.

         <button onClick={()=>{remove(index)}}>Remove</button>

  • push() helps to add new array element to the array

        <button onClick={(event)=>{event.preventDefault();push('')}}>Add</button> 

 

Step 3

Declare the initialValues  , validation function and onSubmit function.

  const validation = (values) => {
    let error = {};
    if (!values.name) {
      error.name = 'Name is required';
    }
    if (!values.password) {
      error.phone = 'Password is required';
    }
    return error;
  }

  const validateSkills = (skill)=>{
    let error;
    if(!skill){
      error = 'Skill Required'
    }
    return error;
  }
 let initialValues={
    name: '',
    password: '',
    skills:[ '' ]
  };

  const onSubmit= (values) => {
    console.log('--values--',values)
  }

Wrap the entire form inside Formik Component and add initialValues={initialValues} validate={validation} onSubmit={onSubmit} as props to Formik component

 

Complete code for Registration Form component

import { Form, Formik, Field, ErrorMessage, FieldArray } from 'formik';



const Registration = () => {


  const validation = (values) => {
    let error = {};
    if (!values.name) {
      error.name = 'Name is required';
    }
    if (!values.password) {
      error.phone = 'Password is required';
    }
    return error;
  }

  const validateSkills = (skill) => {
    let error;
    if (!skill) {
      error = 'Skill Required'
    }
    return error;
  }
  let initialValues = {
    name: '',
    password: '',
    skills: ['']
  };

  const onSubmit = (values) => {
    console.log('--values--', values)
  }

  return (
    <Formik
      initialValues={initialValues}
      validate={validation}
      onSubmit={onSubmit}
    >
      <Form>


        <div>
          <Field name='name'>
            {(props) => {
              const { meta, field } = props;
              /* 
              this field object is having all the properties of a field eg. onChange , type , name , value , onBlur
               and meta object is having all the properties error, initialError, initialTouched, initialValue, touched, value
             */
              return (
                <>
                  <input {...field} placeholder="Enter Name" />
                  <ErrorMessage name='name' />
                </>
              )
            }}
          </Field>
        </div>

        <div>
          <Field name='password'>
            {(props) => {
              const { meta, field } = props;
              return (
                <>
                  <input type='password' {...field} placeholder="Enter password" />
                  <ErrorMessage name='password' />
                </>
              )
            }}
          </Field>
        </div>

        <div>
          <FieldArray name='skills'>
            {(filedArrayObj) => {
              const { form, remove, push } = filedArrayObj;
              const { values } = form;
              const { skills } = values;
              console.log('--skills--', skills)
              return (
                <div>
                  <button onClick={(event) => { event.preventDefault(); push('') }}>Add</button>
                  {
                    skills.map((skill, index) => {
                      return <div key={index}>
                        <Field type="text" placeholder='Skill' name={`skills[${index}]`} validate={validateSkills} />
                        <ErrorMessage name={`skills[${index}]`} />
                        {index > 0 ? <button onClick={() => { remove(index) }}>Remove</button> : null}
                      </div>
                    })
                  }
                </div>
              )
            }}
          </FieldArray>
        </div>
        <div>
          <button type='submit'>Submit</button>
        </div>
      </Form>
    </Formik>
  )
}


export default Registration;



 

 

 

I have not adde any style , my intension was to explain you how to create form in react using formik components .

 

 

 

 

 

 

 

 

 

 

 

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

How to crate basic form in React using Formik

ReactJS 15-03-2023 Saheb Sutradhar

How to crate basic form in React using Formik , react formik example ...

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 ? ...