Building forms in React can be tedious and error-prone. Handling user input, validation, and submission requires a lot of boilerplate code. This is where Formik steps in – it provides an elegant way to manage forms by handling common tasks like getting values, validation, and errors. Combined with Yup validate for validation, creating advanced React forms becomes a breeze.

In this article, we’ll explore advanced techniques for creating better React forms leveraging Formik and Yup validate. We’ll go through practical examples to showcase powerful features like:

  • React Form validation with Yup validate
  • Dynamic forms with arrays and objects
  • Handling form submission
  • Integration with React Query

These examples demonstrate real-world use cases you can apply to build reactive web apps with complex forms. Let’s dive in!

Robust Form Validation with Yup validate

For validation, Formik integrates seamlessly with Yup validate – a JavaScript schema builder. It allows you to create validation schemas declaratively instead of imperatively checking values.

Here is an example signup form schema:

import * as yup from 'yup';

const schema = yup.object().shape({
firstName: yup.string().required(),
age: yup
.number()
.positive()
.integer()
.required(), 
website: yup.string().url(),
});

Yup supports a wide range of validation techniques like:

  • Presence checks – required()nullable()
  • Number/string validation – max(), min(), length()`
  • Custom validators with test()
  • And much more

This eliminates clutter and makes forms more readable.

To integrate with Formik:

import { Formik } from 'formik';

const MyForm = () => (
<Formik
validationSchema={schema}
onSubmit={values => {
// submit form 
}}
>
{/* Form */}
</Formik>
)

Formik will automatically run validation on submit and populate any errors.

Dynamic Forms with Arrays/Objects

Dealing with dynamic nested structures like arrays and objects in forms can be difficult. Formik provides FieldArray and Field components to make this easier.

For example, consider a “friends list” form that allows adding/removing friends:

const FriendListForm = () => (
<Formik
initialValues={{ friends: [] }}
onSubmit={values => {
// submit form
}}
>
{({ values }) => (
<Form>
<FieldArray 
name="friends"
render={arrayHelpers => (
<div>
{values.friends.map((friend, index) => (
<div key={index}>
<Field name={`friends[${index}]`} />
<button 
type="button"
onClick={() => arrayHelpers.remove(index)} 
>
X
</button>
</div>
))}
<button 
type="button"
onClick={() => arrayHelpers.push('')}
>
Add Friend
</button>
</div>
))}
</FieldArray>
<button type="submit">Submit</button>
</Form>
)}
</Formik>
);

The FieldArray component provides convenient helpers like push, pop, remove to manipulate the array.

You can build complex multi-step wizards leveraging these capabilities.

Handling Form Submission

Formik gives you multiple options for handling form submission:

1. Submit Handler

Pass an onSubmit handler to get submitted values:

<Formik
onSubmit={values => {
// submit form 
}}
>

This works for basic cases like submitting directly to an API.

2. Submit Prop

For more control, use the submit prop:

<Formik>
{formik => (
<form onSubmit={formik.submitForm}></form>
)} 
</Formik>

Allows accessing Formik state before submitting.

3. Imperative Submits

Call submitForm imperatively:

import { useFormikContext } from 'formik';

const MyComponent = () => {
const { submitForm } = useFormikContext(); 

const handleClick = () => {
submitForm(); 
}

return (
<button onClick={handleClick}>Submit</button> 
) 
}

This increases flexibility to trigger submission from anywhere.

Integrating with React Query

An excellent Formik companion is React Query – it takes care of remote data management.

Here is an example integration:

import { useMutation } from 'react-query';

function MyForm() {
const { mutate } = useMutation(data => {
return postToAPI(data); 
});

return (
<Formik
onSubmit={(values, actions) => {
mutate(values, {
onSuccess: () => {
actions.resetForm()
} 
})
}}
>
{/* Form */}
</Formik>
);
}

On submit, we call the React Query mutate function and reset form state on success. This simplifies data updates!

React Query handles caching, refetching, error handling and more.

There are many creative ways to leverage Formik React ecosystem libraries like React Query, React Router, Redux and Testing Library.

Conclusion

So that wraps up some advanced form techniques with Formik! Its extensive feature set and integration capabilities make building complex reactive forms a joy. A Formik + Yup combo supercharges form handling in React.

Reach Out to the Experts

Got a web project idea? Let’s talk! I specialize in crafting high-quality React and JavaScript applications leveraging such modern technologies. With over a decade of collective experience, i build robust and scalable web apps optimized for performance, security and scale.