In this project, you will build a React application with advanced form management techniques. You will implement complex forms using libraries like Formik or React Hook Form, add schema validation, and create reusable form components.
# Create a new React project npx create-react-app advanced-form-project # Install dependencies cd advanced-form-project npm install formik yup # or if using React Hook Form npm install react-hook-form @hookform/resolvers yup # Start the development server npm start
// Using Formik import { Formik, Form, Field, ErrorMessage } from 'formik'; import * as Yup from 'yup'; const validationSchema = Yup.object({ firstName: Yup.string() .max(15, 'Must be 15 characters or less') .required('Required'), lastName: Yup.string() .max(20, 'Must be 20 characters or less') .required('Required'), email: Yup.string() .email('Invalid email address') .required('Required'), password: Yup.string() .min(8, 'Password must be at least 8 characters') .required('Required'), confirmPassword: Yup.string() .oneOf([Yup.ref('password'), null], 'Passwords must match') .required('Required') }); function RegistrationForm() { return ( <Formik initialValues={{ firstName: '', lastName: '', email: '', password: '', confirmPassword: '' }} validationSchema={validationSchema} onSubmit={(values, { setSubmitting }) => { setTimeout(() => { alert(JSON.stringify(values, null, 2)); setSubmitting(false); }, 400); }} > {({ isSubmitting }) => ( <Form> <div> <label htmlFor="firstName">First Name</label> <Field name="firstName" type="text" /> <ErrorMessage name="firstName" component="div" className="error" /> </div> <div> <label htmlFor="lastName">Last Name</label> <Field name="lastName" type="text" /> <ErrorMessage name="lastName" component="div" className="error" /> </div> <div> <label htmlFor="email">Email</label> <Field name="email" type="email" /> <ErrorMessage name="email" component="div" className="error" /> </div> <div> <label htmlFor="password">Password</label> <Field name="password" type="password" /> <ErrorMessage name="password" component="div" className="error" /> </div> <div> <label htmlFor="confirmPassword">Confirm Password</label> <Field name="confirmPassword" type="password" /> <ErrorMessage name="confirmPassword" component="div" className="error" /> </div> <button type="submit" disabled={isSubmitting}> {isSubmitting ? 'Submitting...' : 'Submit'} </button> </Form> )} </Formik> ); } export default RegistrationForm;