how to install and use formik in react js?

Hi Friends 👋,

Welcome To aGuideHub!

To install and use formik in React js, you have to use the npm package manager that is how you can install the formik library into your project.

Today, I am going to show you, how to install and use formik in react js.

install and use formik

Install the following packages to use formik in react js.

npm

npm install formik --save

Table of contents

  • Set up the React project.
  • Import necessary components.
  • Use formik.

Step 1: Set up the React project.

First you have to install the React project. You should use create-react-app command to create a new React project.

npx create-react-app my-app
cd my-app
npm start

Step 2: Import necessary components.

After installing formik, you have to import your React component. To do this, add the following line to the top of your component file.

import React from 'react';
import './ExpenseForm.css'
import { Formik } from 'formik';

Step 3: Create a file, ExpenseForm.css.

create a file, ExpenseForm.css under src folder to style the component.

input[type=text], input[type=number], input[type=date], select {
    width: 100%;
    padding: 12px 20px;
    margin: 8px 0;
    display: inline-block;
    border: 1px solid #ccc;
    border-radius: 4px;
    box-sizing: border-box;
 }
 input[type=submit] {
    width: 100%;
    background-color: #4CAF50;
    color: white;
    padding: 14px 20px;
    margin: 8px 0;
    border: none;
    border-radius: 4px;
    cursor: pointer;
 }
 input[type=submit]:hover {
    background-color: #45a049;
 }
 input:focus {
    border: 1px solid #d9d5e0;
 }
 #expenseForm div {
    border-radius: 5px;
    background-color: #f2f2f2;
    padding: 20px;
 }
 #expenseForm span {
    color: red;
 }

React formik example.

The code below is an example of this,The complete code of the ExpenseForm component is given below. Finally, enter a sample expense detail and click submit. The submitted data will be collected and showed in a popup message box.

App.js

import React from 'react';
import './ExpenseForm.css'
import { Formik } from 'formik';

class ExpenseForm extends React.Component {
   constructor(props) {
      super(props);

      this.initialValues = { name: '', amount: '', date: '', category: '' }
   }
   validate = (values) => {
      const errors = {};
      if (!values.name) {
         errors.name = 'Required';
      }
      if (!values.amount) {
         errors.amount = 'Required';
      }
      if (!values.date) {
         errors.date = 'Required';
      }
      if (!values.category) {
         errors.category = 'Required';
      }
      return errors;
   }
   handleSubmit = (values, setSubmitting) => {
      setTimeout(() => {
         alert(JSON.stringify(values, null, 2));
         setSubmitting(false);
      }, 400);
   }
   render() {
      return (
         <div id="expenseForm">
            <Formik
               initialValues={this.initialValues}
               validate={values => this.validate(values)}
               onSubmit={(values, { setSubmitting }) => this.handleSubmit(values, setSubmitting)} > 
               {
                  ({
                     values,
                     errors,
                     touched,
                     handleChange,
                     handleBlur,
                     handleSubmit,
                     isSubmitting,
                     /* and other goodies */
                  }) => 
                  (
                     <form onSubmit={handleSubmit}>
                        <label for="name">Title <span>{errors.name && touched.name && errors.name}</span></label>
                        <input type="text" id="name" name="name" placeholder="Enter expense title"
                           onChange={handleChange}
                           onBlur={handleBlur}
                           value={values.name} />

                        <label for="amount">Amount <span>{errors.amount && touched.amount && errors.amount}</span></label>
                        <input type="number" id="amount" name="amount" placeholder="Enter expense amount"
                           onChange={handleChange}
                           onBlur={handleBlur}
                           value={values.amount} />

                        <label for="date">Spend Date <span>{errors.date && touched.date && errors.date}</span></label>
                        <input type="date" id="date" name="date" placeholder="Enter date"
                           onChange={handleChange}
                           onBlur={handleBlur}
                           value={values.date} />

                        <label for="category">Category <span>{errors.category && touched.category && errors.category}</span></label>
                        <select id="category" name="category"
                           onChange={handleChange}
                           onBlur={handleBlur}
                           value={values.category}>
                           <option value="">Select</option>
                           <option value="Food">Food</option>
                           <option value="Entertainment">Entertainment</option>
                           <option value="Academic">Academic</option>
                        </select>

                        <input type="submit" value="Submit" disabled={isSubmitting} />
                     </form>
                  )
               }
            </Formik>
         </div>
      )
   }
}
export default ExpenseForm;

ExpenseForm.css

input[type=text], input[type=number], input[type=date], select {
    width: 100%;
    padding: 12px 20px;
    margin: 8px 0;
    display: inline-block;
    border: 1px solid #ccc;
    border-radius: 4px;
    box-sizing: border-box;
 }
 input[type=submit] {
    width: 100%;
    background-color: #4CAF50;
    color: white;
    padding: 14px 20px;
    margin: 8px 0;
    border: none;
    border-radius: 4px;
    cursor: pointer;
 }
 input[type=submit]:hover {
    background-color: #45a049;
 }
 input:focus {
    border: 1px solid #d9d5e0;
 }
 #expenseForm div {
    border-radius: 5px;
    background-color: #f2f2f2;
    padding: 20px;
 }
 #expenseForm span {
    color: red;
 }

Check the output of the above code example.

React, formik

Here, we are provided code sandbox links for the above program install and use formik in React js. Then you can use whenever you went and do the changes as per your requirements.

Try it Yourself

All the best 👍

Premium Content

You can get all the below premium content directly in your mail when you subscribe us

Books

Interview Questions

Soon You will get CSS, JavaScript, React Js, and TypeScript So Subscribe to it.

Portfolio Template

View | Get Source Code

Cheat Sheets

Cheat Sheets Books are basically Important useful notes which we use in our day-to-day life.

Related Posts