In my current Ruby on Rails project, I use React for the front end and I have to deal with many forms such as simple single forms and complex multi steps forms. Generally, as you know I have to handle form element states, validate the element values, submit form values to the API, render forms with values from the API response etc.
In React, you can use React form to fulfill your requirements, but I decided to use Formik instead.
What is Formik?
Formik is a handy set of React components and hooks for building simple and complex forms in React and React Native. It provides three most common advantages:
Getting values in and out of form state
Validation and error messages
Handling form submission
By colocating all these in one place, Formik keeps things organized—making testing, refactoring, and reasoning about your forms a breeze.
Basic Formik form
import React from 'react';
import { Formik } from 'formik';
const BasicExample = () => (
<div>
<h1>My Form</h1>
<Formik
initialValues={{ name: 'jared' }}
onSubmit={(values, actions) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
actions.setSubmitting(false);
}, 1000);
}}
>
{props => (
<form onSubmit={props.handleSubmit}>
<input
type="text"
onChange={props.handleChange}
onBlur={props.handleBlur}
value={props.values.name}
name="name"
/>
{props.errors.name && <div id="feedback">{props.errors.name}</div>}
<button type="submit">Submit</button>
</form">
)}
</Formik>
</div>
);
The prop initialvalues
define the default value of jared
for the name input control in the form and the value will be displayed when the form component is rendered.
Additionally, to get the initialvalues
synched with API response data, you can add a prop enableReinitialize={true}
to the form.
<Formik
enableReinitialize={true}
initialValues={{ name: ApiResonseDataName || 'jared' }}
...
>
Please notice that if you don't enable that option, you will always get the default initial value.
Conclusion
I've chosen Formik over pure React forms because it provides me with helpful functionalities for developing even complex forms very conveniently. And I hope this simple tip helps you save time on your development when working on Formik and API integration.