Formik is a form management library tailored for React. It is designed to simplify handling form states, validation, and submissions. It provides developers with an efficient toolset to manage forms in React, reducing boilerplate and enhancing maintainability. This Answer will explore the useFormik hook to implement forms in React, demonstrating Formik’s capability to streamline form management.
Before we dive into Formik, let’s examine a basic form implementation using React’s useState hook.
While React’s useState and other hooks offer basic state management capabilities, they can become cumbersome in complex form scenarios, requiring extensive boilerplate code for handling validations, error messages, and form submissions.
Formik addresses these challenges by providing a comprehensive solution that encapsulates form state management, validation, and error handling in a more structured and less error-prone manner. It simplifies form development, making it easier to maintain and scale, especially in applications with numerous or complex forms.
Now that we've explored a basic form implementation in React, let’s transition to leveraging Formik.
In the React project, install formik
using the following command:
npm install --save formik# oryarn add formik
The useFormik hook is a custom hook provided by the Formik library in React that helps manage form state and form submissions. It simplifies the process of building forms in React by handling the form state, validation, and submission, reducing the amount of boilerplate code needed.
Here is a basic structure for implementing the useFormik
hook:
import { useFormik } from 'formik';const YourComponent = () => {const formik = useFormik({initialValues: {// Define form fields and initial values},onSubmit: (values) => {// Handle form submission (e.g., make API call, update state, etc.)},validate: (values) => {// Validation logic for each field},});return (// Your form components and UI elements);};export default YourComponent;
The useFormik
hook facilitates form management in React:
initialValues
: It sets the starting values for form fields, typically an object where keys are field names and values are their initial content.
onSubmit
: It’s a function that defines what happens when the form is submitted. It receives the form’s current values and can be used to, for example, send data to a server.
validate
: It’s a function that checks the input values against validation rules and returns an object with errors. If a field’s value is invalid, the function should add a corresponding message to the errors object under the field's name.
By organizing these aspects within useFormik
, we encapsulate all essential form logic, making our component cleaner and more maintainable.
Integrate form fields using the TextField
components from material UI or HTML input elements.
<inputtype="text"id="fullName"name="fullName"placeholder="Full Name"onChange={formik.handleChange} // in-built change handlervalue={formik.values.fullName}/>
In the React application below, we have created a simple contact us form using formik
. Click the “Run” button below to check the output.
In the output below, enter the information in the fields and upon submission an “alert” will show the details.
Lines 1–2: The code begins by importing React
and the useFormik
hook from the Formik library, which will be used for managing form state and behavior.
Lines 4–15: The App
functional component is defined. Inside this component, the useFormik
hook is called to initialize the form state and behavior. It takes an object with configuration options:
initialValues
: This is an object defining the initial values for the form fields (fullName
, email
, and phoneNumber
).
onSubmit
: This is a function that will be called when the form is submitted. It logs the form values to the console and alerts a formatted JSON string representation of the values.
Lines 17–56: The JSX markup is returned, defining the structure of the component. It includes:
A <div>
containing a <h4>
heading (“Contact Us”)
Inside a <form>
element, there are three <input>
elements for capturing the user's full name, email, and phone number respectively
Each input element is connected to Formik via props:
onChange
is set to formik.handleChange
, which updates the Formik state when the input value changes.
value
is set to formik.values.fieldName
, which binds the input value to the corresponding field in the Formik state.
There is also a <button>
element inside the form for submitting the form.
Line 58: The App
component is exported as the default export from this module, making it available for use elsewhere in the application.
This Answer showcases the utilization of Formik, a React library, to efficiently manage form state and handling within the ContactUs
functional component.
Free Resources