Formik + Yup

Reducing Boilerplate

GetFeildProps()

Để tiết kiệm thời gian nên dùng form.getFeildProps().
(The code above is very explicit about exactly what Formik is doing. onChange -> handleChange, onBlur -> handleBlur, and so on. However, to save you time, useFormik() returns a helper method called formik.getFieldProps() to make it faster to wire up inputs. Given some field-level info, it returns to you the exact group of onChange, onBlur, value, checked for a given field. You can then spread that on an input, select, or textarea.)
1 import React from 'react';
2 import { useFormik } from 'formik';
3 import * as Yup from 'yup';
4
5 const SignupForm = () => {
6 const formik = useFormik({
7 initialValues: {
8 firstName: '',
9 lastName: '',
10 email: '',
11 },
12 validationSchema: Yup.object({
13 firstName: Yup.string()
14 .max(15, 'Must be 15 characters or less')
15 .required('Required'),
16 lastName: Yup.string()
17 .max(20, 'Must be 20 characters or less')
18 .required('Required'),
19 email: Yup.string().email('Invalid email address').required('Required'),
20 }),
21 onSubmit: values => {
22 alert(JSON.stringify(values, null, 2));
23 },
24 });
25 return (
26 <form onSubmit={formik.handleSubmit}>
27 <label htmlFor="firstName">First Name</label>
28 <input
29 id="firstName"
30 type="text"
31 {...formik.getFieldProps('firstName')}
32 />
33 {formik.touched.firstName && formik.errors.firstName ? (
34 <div>{formik.errors.firstName}</div>
35 ) : null}
36
37 <label htmlFor="lastName">Last Name</label>
38 <input id="lastName" type="text" {...formik.getFieldProps('lastName')} />
39 {formik.touched.lastName && formik.errors.lastName ? (
40 <div>{formik.errors.lastName}</div>
41 ) : null}
42
43 <label htmlFor="email">Email Address</label>
44 <input id="email" type="email" {...formik.getFieldProps('email')} />
45 {formik.touched.email && formik.errors.email ? (
46 <div>{formik.errors.email}</div>
47 ) : null}
48
49 <button type="submit">Submit</button>
50 </form>
51 );
52 };

Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.