Make a Basic Form Using React and Formik.

Create a Basic Form using React and Formik

This is how our Basic-Form is going to appear πŸ‘‡

Basic form using React, formik and yup

The first step would be setting up our React application and for that, you need to choose a development environment. For this project, we’ll use create-react-app, but feel free to choose another environment that suits your preferences.

To setup your react application follow these steps :

1. Run the following command in your terminal:

npx create-react-app my-app

if the above command doesn’t work, run this command:

npm init react-app my-app

2. Navigate to the root directory of your new React app:

cd my-app

3. Run your build process with `npm start`:

npm start

We have setup our react application, Now we will create the UI of our Basic Form.

Creating UI :-

Note: If you would like to save time and avoid the task of creating a user interface, you can easily access the UI code from my GitHub repository. Simply
Click here. The main code for the app can be found in the App.js file, and the styling code is in index.css.

To create the user interface (UI), we will begin by adding a <div> element with the className attribute set to “form-container” in the App.js file. Inside this <div>, we will create a <form> element with the className attribute set to “register-form”. Within the <form> element, we will include three <input> elements and a button labeled “Register”.

The first <input> element will be used for entering the user’s “First Name”, the second <input> element will be for the “Last Name”, and the third <input> element will be used to capture the user’s “email” address. The “Register” button will be used to submit the form.

App.js : πŸ‘‡

import "./App.css";

function App() {
  return (
    <div className="form-container">
      <form className="register-form">
        <input
          id="first-name"
          className="form-field"
          type="text"
          placeholder="First Name"
          name="firstName"
        />

        <input
          id="last-name"
          className="form-field"
          type="text"
          placeholder="Last Name"
          name="lastName"
        />

        <input
          id="email"
          className="form-field"
          type="text"
          placeholder="Email"
          name="email"
        />

        <button className="form-field" type="submit">
          Register
        </button>
      </form>
    </div>
  );
}

export default App;

Now your Form should look like thisπŸ‘‡:

Basic-Form

Now that we have finished creating the user interface (UI), we will move on to the next step.

What is Formik & Installation:-

Formik is a library that helps developers build forms for websites or applications. A form is like a digital version of a paper form, where you enter information like your name, email, or other details. Formik makes it easier for developers to create and manage these forms by providing a set of tools and rules.

To install formik in your project you just need follow these steps :

1. Navigate to the root directory of your Basic Form app:

cd my-app

2. Install formik :

npm i formik

This command will install Formik and add it as a dependency in your project’s package.json file.

Handling Form:-

We will use useFormik() hook to handle our Form. “useFormik” is a hook provided by the Formik library that helps you handle forms in your React application.

When you use “useFormik“, you start by giving it some initial values for your form fields, just like when you start with an empty piece of paper. Then, you define a function to handle what should happen when the form is submitted, like when you finish writing on the paper and want to do something with it.

App.js : πŸ‘‡

const formik = useFormik({
    initialValues: {
      firstName: "",
      lastName: "",
      email: "",
    },
  });

Once you have set up the initial values and the submit function, “useFormik” gives you a set of tools that make it easier to work with your form. These tools include special variables and functions that you can use to access and manipulate the form values, handle validation, and more.

For example, you can use the “values” variable to access the current values of your form fields, just like reading what you’ve written on the paper. You can also use the “handleChange” function to update the values as you type, like when you change your writing on the paper.

App.js : πŸ‘‡

 <div className="form-container">
      <form className="register-form">
        <input
          id="firstName"
          className="form-field"
          type="text"
          placeholder="First Name"
          name="firstName"
          value={formik.values.firstName}
          onChange={formik.handleChange}
        />

        <input
          id="lastName"
          className="form-field"
          type="text"
          placeholder="Last Name"
          name="lastName"
          value={formik.values.lastName}
          onChange={formik.handleChange}
        />

        <input
          id="email"
          className="form-field"
          type="text"
          placeholder="Email"
          name="email"
          value={formik.values.email}
          onChange={formik.handleChange}
        />

        <button className="form-field" type="submit">
          Register
        </button>
      </form>
    </div>

useFormik” also provides a “handleSubmit” function that you can call when you want to trigger the form submission. It takes care of calling your submit function and passing the form values to it, just like when you finish writing and hand over the paper to someone else.

App.js : πŸ‘‡

// function App() {
  const submit = (values) => {
    console.log("values", values);
  };

//  const formik = useFormik({
//    initialValues: {
//      firstName: "",
//      lastName: "",
//      email: "",
//    },
    onSubmit: submit,
//  });

//  return (
//    <div className="form-container">
      <form onSubmit={formik.handleSubmit} className="register-form">

Validation :-

To validate our form we will use a library called yup. Yup provides a simple and declarative way to define validation schemas for your forms. It allows you to define rules and constraints for each form field, such as required fields, minimum and maximum length, specific formats (like email or URL), and more.

Install and use yup by following these steps:

1. Navigate to the root directory of your Basic Form app :

cd my-app

2. Install yup using npm :

npm i yup

3. Import the necessary modules:

import * as Yup from 'yup';

4. Define a validation schema using Yup:

To use Yup for form validation, we will create a variable called “schema” that will define the validation rules for our input fields based on their names. We will specify the validation criteria for each field within this schema variable.

Next, we will include this “schema” variable in the “validationSchema” property of the “useFormik” hook. This allows us to apply the defined validation rules to our form fields and handle validation errors accordingly.

App.js : πŸ‘‡

//import "./App.css";
//import { useFormik } from "formik";
import * as Yup from "yup";

// function App() {
//  const submit = (values) => {};

  const schema = Yup.object().shape({
    firstName: Yup.string().required(),
    lastName: Yup.string().required(),
    email: Yup.string().email().required(),
  });

//  const formik = useFormik({
//    initialValues: {
//      firstName: "",
//      lastName: "",
//      email: "",
//    },
//    onSubmit: submit,
    validationSchema: schema,
//  });

//  return (
//    <div className="form-container">
//      <form onSubmit={formik.handleSubmit} className="register-form">
//        <input
//          id="firstName"
//          className="form-field"
//          type="text"
//          placeholder="First Name"
//          name="firstName"
//          value={formik.values.firstName}
//          onChange={formik.handleChange}
//        />
//        <span className="">error</span>
//        <input
//          id="lastName"
//          className="form-field"
//          type="text"
//          placeholder="Last Name"
//          name="lastName"
//          value={formik.values.lastName}
//          onChange={formik.handleChange}
//        />
//        <span className="">error</span>
//        <input
//          id="email"
//          className="form-field"
//          type="text"
//          placeholder="Email"
//          name="email"
//          value={formik.values.email}
//          onChange={formik.handleChange}
//        />
//        <span className="">error</span>

//        <button className="form-field" type="submit">
//          Register
//        </button>
  //    </form>
 //   </div>
//  );
// }

//  export default App;

To validate the inputs, we will use conditional statements like if-else. like we will check if the user has left the input field empty and clicked the button. If this happens, we will display an error message which “yup” provides us, asking the user to fill out the input before proceeding. This helps ensure that the user is reminded to provide the required information before submitting the form.

App.js : πŸ‘‡

//import "./App.css";
//import { useFormik } from "formik";
// import * as Yup from "yup";

// function App() {
//  const submit = (values) => {};

//  const schema = Yup.object().shape({
//    firstName: Yup.string().required(),
//    lastName: Yup.string().required(),
//    email: Yup.string().email().required(),
//  });

//  const formik = useFormik({
//    initialValues: {
//      firstName: "",
//      lastName: "",
//      email: "",
//    },
//    onSubmit: submit,
//    validationSchema: schema,
//  });

//  return (
//    <div className="form-container">
//      <form onSubmit={formik.handleSubmit} className="register-form">
//        <input
//          id="firstName"
//          className="form-field"
//          type="text"
//          placeholder="First Name"
//          name="firstName"
//          value={formik.values.firstName}
//          onChange={formik.handleChange}
//        />
         {formik.errors.firstName && formik.touched.firstName && (
          <span className=""> {formik.errors.firstName}</span>
        )}
//        <input
//          id="lastName"
//          className="form-field"
//          type="text"
//          placeholder="Last Name"
//          name="lastName"
//          value={formik.values.lastName}
//          onChange={formik.handleChange}
//        />
        {formik.errors.lastName && formik.touched.lastName && (
          <span className=""> {formik.errors.lastName}</span>
        )}
//        <input
//          id="email"
//          className="form-field"
//          type="text"
//          placeholder="Email"
//          name="email"
//          value={formik.values.email}
//          onChange={formik.handleChange}
//        />
         {formik.errors.email && formik.touched.email && (
          <span className=""> {formik.errors.email}</span>
        )}

//        <button className="form-field" type="submit">
//          Register
//        </button>
  //    </form>
 //   </div>
//  );
// }

//  export default App;

Form Submission :-

To achieve this, we will create a state variable called “registered” with an initial value of “false”. Then, in the “submit” function, we will use the “setRegistered” function to update the value of “registered” to the opposite of its current value.

This means that when the user clicks the “Register” button to submit the form, the “setRegistered” function will toggle the value of “registered” from true to false or from false to true. This will allow us to track the success state of the form submission and display the corresponding message.

At the end when the form is submitted we will show a success message to the user that your form has been submitted.

App.js : πŸ‘‡

//import "./App.css";
//import { useFormik } from "formik";
// import * as Yup from "yup";

// function App() {
     const [registered, setRegistered] = useState(false);

//  const submit = () => {
    setRegistered(!registered);
//  };
//  const schema = Yup.object().shape({
//    firstName: Yup.string().required(),
//    lastName: Yup.string().required(),
//    email: Yup.string().email().required(),
//  });

//  const formik = useFormik({
//    initialValues: {
//      firstName: "",
//      lastName: "",
//      email: "",
//    },
//    onSubmit: submit,
//    validationSchema: schema,
//  });

//  return (
//    <div className="form-container">
//      <form onSubmit={formik.handleSubmit} className="register-form">
 {registered && (
          <div className="success-message">Your form has been submited</div>
        )}
//        <input
//          id="firstName"
//          className="form-field"
//          type="text"
//          placeholder="First Name"
//          name="firstName"
//          value={formik.values.firstName}
//          onChange={formik.handleChange}
//        />
//         {formik.errors.firstName && formik.touched.firstName && (
//          <span className=""> {formik.errors.firstName}</span>
//        )}
//        <input
//          id="lastName"
//          className="form-field"
//          type="text"
//          placeholder="Last Name"
//          name="lastName"
//          value={formik.values.lastName}
//          onChange={formik.handleChange}
//        />
//        {formik.errors.lastName && formik.touched.lastName && (
//          <span className=""> {formik.errors.lastName}</span>
//        )}
//        <input
//          id="email"
//          className="form-field"
//          type="text"
//          placeholder="Email"
//          name="email"
//          value={formik.values.email}
//          onChange={formik.handleChange}
//        />
//         {formik.errors.email && formik.touched.email && (
//          <span className=""> {formik.errors.email}</span>
//        )}

//        <button className="form-field" type="submit">
//          Register
//        </button>
  //    </form>
 //   </div>
//  );
// }

//  export default App;

Full Code : App.js πŸ‘‡

import "./App.css";
import { useFormik } from "formik";
import { useState } from "react";
import * as Yup from "yup";

function App() {
  const [registered, setRegistered] = useState(false);

  const submit = () => {
    setRegistered(!registered);
  };

  const schema = Yup.object().shape({
    firstName: Yup.string().required(),
    lastName: Yup.string().required(),
    email: Yup.string().email().required(),
  });

  const formik = useFormik({
    initialValues: {
      firstName: "",
      lastName: "",
      email: "",
    },
    onSubmit: submit,
    validationSchema: schema,
  });

  return (
    <div className="form-container">
      <form onSubmit={formik.handleSubmit} className="register-form">
        {registered && (
          <div className="success-message">Your form has been submited</div>
        )}
        <input
          id="firstName"
          className="form-field"
          type="text"
          placeholder="First Name"
          name="firstName"
          value={formik.values.firstName}
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
        />
        {formik.errors.firstName && formik.touched.firstName && (
          <span className=""> {formik.errors.firstName}</span>
        )}

        <input
          id="lastName"
          className="form-field"
          type="text"
          placeholder="Last Name"
          name="lastName"
          value={formik.values.lastName}
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
        />
        {formik.errors.lastName && formik.touched.lastName && (
          <span className=""> {formik.errors.lastName}</span>
        )}

        <input
          id="email"
          className="form-field"
          type="text"
          placeholder="Email"
          name="email"
          value={formik.values.email}
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
        />
        {formik.errors.email && formik.touched.email && (
          <span className=""> {formik.errors.email}</span>
        )}

        <button className="form-field" type="submit">
          Register
        </button>
      </form>
    </div>
  );
}

export default App;

Here we have completed the Basic-Form application Tutorial. I hope you liked it πŸ™

ALSO SEE – HOW TO MAKE A SEARCH FILTER USING REACT.
ALSO SEE – HOW TO MAKE A TEMPERATURE CONTROLLER USING REACT.

,

Leave a Reply

Your email address will not be published. Required fields are marked *