Formik tutorial in REACT with full coding examples?
- Get link
- X
- Other Apps
Formik Tutorial in React with Full Coding Example
Formik is a popular library for handling forms in React. It simplifies managing form state, validation, and submission handling. In this tutorial, I'll guide you through using Formik to build a form in React with full coding examples, including form validation and handling form submission.
Step 1: Set up a React project
If you haven't already created a React project, you can start by using Create React App:
npx create-react-app formik-tutorial
cd formik-tutorial
Step 2: Install Formik and Yup
We need to install Formik for form handling and Yup for validation. Run the following command to install them:
npm install formik yup
- Formik: Handles form state and submission.
- Yup: A JavaScript schema validator to help with form validation.
Step 3: Basic Formik Form Example
Let's start by building a simple form with Formik. We'll create a form where a user can input their name and email.
Create the FormComponent.js
file:
// src/FormComponent.js
import React from "react";
import { Formik, Field, Form, ErrorMessage } from "formik";
const FormComponent = () => {
return (
<div className="max-w-md mx-auto p-4 bg-gray-100 rounded-lg shadow-md">
<h2 className="text-xl font-bold mb-4">Formik Example</h2>
<Formik
initialValues={{
name: "",
email: "",
}}
onSubmit={(values) => {
console.log("Form data", values);
}}
>
{() => (
<Form>
<div className="mb-4">
<label htmlFor="name" className="block text-sm font-semibold">
Name
</label>
<Field
id="name"
name="name"
type="text"
className="mt-2 p-2 w-full border rounded"
/>
<ErrorMessage
name="name"
component="div"
className="text-red-500 text-sm mt-1"
/>
</div>
<div className="mb-4">
<label htmlFor="email" className="block text-sm font-semibold">
Email
</label>
<Field
id="email"
name="email"
type="email"
className="mt-2 p-2 w-full border rounded"
/>
<ErrorMessage
name="email"
component="div"
className="text-red-500 text-sm mt-1"
/>
</div>
<button
type="submit"
className="w-full py-2 bg-blue-500 text-white rounded"
>
Submit
</button>
</Form>
)}
</Formik>
</div>
);
};
export default FormComponent;
Explanation:
- Formik Component: The
Formik
component wraps the form and provides context for form handling.initialValues
: Initial values for the form fields.onSubmit
: A callback function that handles the form submission.
- Field Component: A wrapper around your form elements to hook them into Formik's state.
- ErrorMessage Component: Displays validation error messages.
Step 4: Add Form Validation with Yup
Now, let's enhance the form with Yup validation. We'll add validation to ensure the name field is required and that the email field is valid.
Update the FormComponent.js
to include Yup validation:
// src/FormComponent.js
import React from "react";
import { Formik, Field, Form, ErrorMessage } from "formik";
import * as Yup from "yup"; // Import Yup for validation
// Validation schema using Yup
const validationSchema = Yup.object({
name: Yup.string().required("Name is required"), // Name is required
email: Yup.string()
.email("Invalid email format")
.required("Email is required"), // Email is required and should be valid
});
const FormComponent = () => {
return (
<div className="max-w-md mx-auto p-4 bg-gray-100 rounded-lg shadow-md">
<h2 className="text-xl font-bold mb-4">Formik with Yup Example</h2>
<Formik
initialValues={{
name: "",
email: "",
}}
validationSchema={validationSchema} // Apply validation schema
onSubmit={(values) => {
console.log("Form data", values);
}}
>
{() => (
<Form>
<div className="mb-4">
<label htmlFor="name" className="block text-sm font-semibold">
Name
</label>
<Field
id="name"
name="name"
type="text"
className="mt-2 p-2 w-full border rounded"
/>
<ErrorMessage
name="name"
component="div"
className="text-red-500 text-sm mt-1"
/>
</div>
<div className="mb-4">
<label htmlFor="email" className="block text-sm font-semibold">
Email
</label>
<Field
id="email"
name="email"
type="email"
className="mt-2 p-2 w-full border rounded"
/>
<ErrorMessage
name="email"
component="div"
className="text-red-500 text-sm mt-1"
/>
</div>
<button
type="submit"
className="w-full py-2 bg-blue-500 text-white rounded"
>
Submit
</button>
</Form>
)}
</Formik>
</div>
);
};
export default FormComponent;
Explanation of Yup Validation:
- Yup Schema: We define a schema using Yup. Each field is validated according to the rules specified:
name
: It is a required string field.email
: It must be a valid email format and required.
- validationSchema: This is passed to the Formik component to handle the validation logic.
Step 5: Use the Form Component
Now, integrate the FormComponent
into the main App.js
file.
// src/App.js
import React from "react";
import FormComponent from "./FormComponent"; // Import the form component
const App = () => {
return (
<div className="App">
<FormComponent />
</div>
);
};
export default App;
Step 6: Styling with Tailwind CSS
If you haven't set up Tailwind CSS in your project, follow these steps to install and configure it:
Install Tailwind via npm:
npm install -D tailwindcss postcss autoprefixer
Create a
tailwind.config.js
file:bashnpx tailwindcss init
Add Tailwind to your
src/index.css
:/* src/index.css */ @tailwind base; @tailwind components; @tailwind utilities;
Build and run the app:
npm start
This will give you a form that looks great with minimal effort, thanks to Tailwind CSS.
Step 7: Testing the Form
When you open your app, the form will have fields for Name
and Email
. The Name
field is required, and the Email
field must be a valid email. If you try to submit without filling the fields or entering invalid data, you will see validation error messages below each field.
Example Error Messages:
- Name: "Name is required"
- Email: "Email is required" or "Invalid email format"
Final Thoughts
In this tutorial, you've learned how to:
- Create a form using Formik.
- Validate the form fields using Yup.
- Style the form with Tailwind CSS.
Formik and Yup provide a powerful and easy-to-use solution for handling forms in React applications. You can extend this setup to create more complex forms with multiple fields, dynamic validation, and more sophisticated form handling logic.
Happy coding!
- Get link
- X
- Other Apps
Comments
Post a Comment