Formik is a popular library for managing forms in React applications. It simplifies form handling by managing state, validation, and submission processes. Here’s a step-by-step tutorial to help you get started with Formik.
First, make sure you have a React application set up. You can create a new one using Create React App if you don’t already have one:
npx create-react-app my-formik-app
cd my-formik-app
Install Formik using npm or yarn:
npm install formik
# or
yarn add formik
Let’s create a simple form to collect user information (name and email).
MyForm.js
):import React from 'react';
import { useFormik } from 'formik';
const MyForm = () => {
const formik = useFormik({
initialValues: {
name: '',
email: '',
},
onSubmit: values => {
alert(JSON.stringify(values, null, 2));
},
});
return (
<form onSubmit={formik.handleSubmit}>
<div>
<label htmlFor="name">Name</label>
<input
id="name"
name="name"
type="text"
onChange={formik.handleChange}
value={formik.values.name}
/>
</div>
<div>
<label htmlFor="email">Email</label>
<input
id="email"
name="email"
type="email"
onChange={formik.handleChange}
value={formik.values.email}
/>
</div>
<button type="submit">Submit</button>
</form>
);
};
export default MyForm;
App.js
):import React from 'react';
import MyForm from './MyForm';
const App = () => (
<div>
<h1>My Formik Form</h1>
<MyForm />
</div>
);
export default App;
Formik provides an easy way to add validation to your forms. We’ll use Yup, a popular validation library.
npm install yup
# or
yarn add yup
import React from 'react';
import { useFormik } from 'formik';
import * as Yup from 'yup';
const MyForm = () => {
const formik = useFormik({
initialValues: {
name: '',
email: '',
},
validationSchema: Yup.object({
name: Yup.string()
.max(15, 'Must be 15 characters or less')
.required('Required'),
email: Yup.string()
.email('Invalid email address')
.required('Required'),
}),
onSubmit: values => {
alert(JSON.stringify(values, null, 2));
},
});
return (
<form onSubmit={formik.handleSubmit}>
<div>
<label htmlFor="name">Name</label>
<input
id="name"
name="name"
type="text"
onChange={formik.handleChange}
onBlur={formik.handleBlur}
value={formik.values.name}
/>
{formik.touched.name && formik.errors.name ? (
<div>{formik.errors.name}</div>
) : null}
</div>
<div>
<label htmlFor="email">Email</label>
<input
id="email"
name="email"
type="email"
onChange={formik.handleChange}
onBlur={formik.handleBlur}
value={formik.values.email}
/>
{formik.touched.email && formik.errors.email ? (
<div>{formik.errors.email}</div>
) : null}
</div>
<button type="submit">Submit</button>
</form>
);
};
export default MyForm;
Formik provides more features to handle complex forms. Here’s a brief overview of some additional functionalities:
Field
component.import { Formik, Field, Form, ErrorMessage } from 'formik';
import * as Yup from 'yup';
const MyForm = () => (
<Formik
initialValues={{ name: '', email: '' }}
validationSchema={Yup.object({
name: Yup.string()
.max(15, 'Must be 15 characters or less')
.required('Required'),
email: Yup.string()
.email('Invalid email address')
.required('Required'),
})}
onSubmit={(values, { setSubmitting }) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
setSubmitting(false);
}, 400);
}}
>
<Form>
<div>
<label htmlFor="name">Name</label>
<Field name="name" type="text" />
<ErrorMessage name="name" />
</div>
<div>
<label htmlFor="email">Email</label>
<Field name="email" type="email" />
<ErrorMessage name="email" />
</div>
<button type="submit">Submit</button>
</Form>
</Formik>
);
export default MyForm;
Handling Arrays: Use Formik’s FieldArray
for managing arrays of fields.
Dynamic Forms: Create forms that can add/remove fields dynamically based on user input.
Formik is a powerful tool for handling forms in React applications, providing an easy way to manage form state, validation, and submission. With its integration with Yup, you can handle complex validation logic with ease. This tutorial covers the basics, but Formik has many more features that you can explore in its official documentation.