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 .