Formik and Yup are popular libraries in the React ecosystem that simplify form handling and validation. Here's a step-by-step guide on how to use Formik and Yup in your React app:
- Install Dependencies: Make sure you have Formik and Yup installed in your project.
npm install formik yup
-
Create a Form Component:
Create a new React component for your form. For example,
LoginForm.js
.
// LoginForm.js
import React from 'react';
import { Formik, Form, Field, ErrorMessage } from 'formik';
import * as Yup from 'yup';
const LoginForm = () => {
return (
<Formik
initialValues={{
email: '',
password: '',
}}
validationSchema={Yup.object({
email: Yup.string().email('Invalid email address').required('Required'),
password: Yup.string().required('Required'),
})}
onSubmit={(values, { setSubmitting }) => {
// Handle form submission logic here
console.log(values);
setSubmitting(false);
}}
>
<Form>
<label htmlFor="email">Email</label>
<Field type="email" name="email" />
<ErrorMessage name="email" component="div" />
<label htmlFor="password">Password</label>
<Field type="password" name="password" />
<ErrorMessage name="password" component="div" />
<button type="submit">Submit</button>
</Form>
</Formik>
);
};
export default LoginForm;
-
Explanation:
-
Formik
: The main wrapper component for managing the form state and handling form submission. -
Form
: The HTML form element that wraps your form fields. -
Field
: Represents a form input field, and you can use it for various input types (text
,password
,email
, etc.). -
ErrorMessage
: Displays validation errors for a specific field.
-
-
Validation with Yup:
- The
validationSchema
prop inFormik
is used to define the validation rules using Yup. - In the example, we defined rules for the
email
andpassword
fields using theYup.string()
schema methods.
- The
-
Handle Form Submission:
- The
onSubmit
prop inFormik
is a function that will be called when the form is submitted. - You can handle your form submission logic inside this function.
- The
Usage:
Import and use theLoginForm
component in your main application file (e.g.,App.js
).
// App.js
import React from 'react';
import LoginForm from './LoginForm';
const App = () => {
return (
<div>
<h1>Login Form</h1>
<LoginForm />
</div>
);
};
export default App;
Now, you have a basic form with validation using Formik and Yup in your React app. Customize the form structure and validation rules according to your specific requirements.
Top comments (0)