...

/

The formik.getFieldProps Method

The formik.getFieldProps Method

Learn how to use the formik.getFieldProps method to reduce the repeated code written for each field in a Formik form.

We'll cover the following...

Problem statement

When we create a form with Formik and the useFormik hook, we repeat the same lines of code for each field we add.

Press + to interact
// ...
return (
// ...
<form onSubmit={formik.handleSubmit}>
<label htmlFor="name">Name</label>
<input
type="text"
id="name"
name="name"
onChange={formik.handleChange}
onBlur={formik.handleBlur}
value={formik.values.name}
/>
{formik.errors.name && formik.touched.name && (
<small>{formik.errors.name}</small>
)}
<label htmlFor="email">Email</label>
<input
type="text"
id="email"
name="email"
onChange={formik.handleChange}
onBlur={formik.handleBlur}
value={formik.values.email}
/>
{formik.errors.email && formik.touched.email && (
<small>{formik.errors.email}</small>
)}
<label htmlFor="phone">Phone Number</label>
<input
type="text"
id="phone"
name="phone"
onChange={formik.handleChange}
onBlur={formik.handleBlur}
value={formik.values.phone}
/>
{formik.errors.phone && formik.touched.phone && (
<small>{formik.errors.phone}</small>
)}
<label htmlFor="address">Address</label>
<input
type="text"
id="address"
name="address"
onChange={formik.handleChange}
onBlur={formik.handleBlur}
value={formik.values.address}
/>
{formik.errors.address && formik.touched.address && (
<small>{formik.errors.address}</small>
)}
// ...
</form>
</section>
);
// ...

We see that the lines of code that specify the onChange, onBlur, and value props for each field were repeated. As we add more fields, we must repeat these lines. It’s a general principle in software development that when we write the same code over and over again, there’s a better way to test and improve your code. This is the rule of DRY (Don’t Repeat Yourself). This rule helps us save time and improve the ...