Create a login form using formik in react js
Today’s article will demonstrate how to develop a login form in react js using formik. Formik is one of the greatest react js packages available for quickly creating forms. Without a hitch, Formik and Yup construct a form with validation. I use formik to generate all of my forms since it has everything I need to make a form. So let’s get started on how to make a login form in formik.
Requirements
- First, we have to create our login form and for that, we will paste the below HTML and CSS code to our app.js and app.css file.
This is how the form will look.
2. Now it’s time to install the required modules. Open your terminal and run the below command to install those modules.
npm install formik yup
3. Now import formik and yup to our app.js file
import { Formik } from "formik";
import * as Yup from "yup";
4. We should then use the yup module to create a schema for validation. Inside the app.js file, paste the following code just above your functional component code.
const schema = Yup.object().shape({
email: Yup.string()
.required("Email is a required field")
.email("Invalid email format"),
password: Yup.string()
.required("Password is a required field")
.min(8, "Password must be at least 8 characters"),
});
5. Now we must wrap our form within our formik tag and call the necessary props for formik to function. There are mainly three props which we have to consider which is
- validationSchema — pass our schema for validation here
- initialValues — create initial value for the form
- onSubmit- Clicking on submit button to perform any action
Other props are available, but you must first read the Formik doc to determine which ones are required for your situation.
Simply copy and paste the code below into your app.js file. Every line has a javascript comment explaining it.
That’s it; now, if you click the submit button and fill out the form, it will alert you to the entered values, and if you submit it blank, it will display an error message.
For any query, you can get in touch with me via LinkedIn
Below you can find the sample GitHub Repository and demo on code sandbox.