Design Converter
Education
Last updated on Feb 24, 2025
•5 mins read
Last updated on Feb 24, 2025
•5 mins read
Struggling to manage form input in React?
Handling user input can get messy, especially with multiple fields. Writing separate functions for each field takes time and adds extra code.
That's where Formik handleChange helps. It simplifies form handling by managing onChange events automatically. This keeps your code clean and makes forms easier to manage.
This blog walks through how it works, ways to customize it, and how to use it inside a React component.
Let's get started!
Formik handleChange is an event handler that updates form values when an input field changes. It abstracts the process of managing state updates in form components.
When a user types into an input field, Formik handleChange updates the corresponding value in formik.state. This ensures that form values stay in sync with user input.
Here’s how Formik handleChange is used in a React component:
1import React from "react"; 2import { useFormik } from "formik"; 3 4const MyForm = () => { 5 const formik = useFormik({ 6 initialValues: { email: "", username: "" }, 7 onSubmit: (values) => { 8 console.log("Form submitted:", values); 9 }, 10 }); 11 12 return ( 13 <form onSubmit={formik.handleSubmit}> 14 <input 15 type="text" 16 name="username" 17 onChange={formik.handleChange} 18 value={formik.values.username} 19 /> 20 <input 21 type="email" 22 name="email" 23 onChange={formik.handleChange} 24 value={formik.values.email} 25 /> 26 <button type="submit">Submit</button> 27 </form> 28 ); 29}; 30 31export default MyForm;
• useFormik initializes form values and manages the submission process.
• formik.handleChange updates the form state when an input field is modified.
• formik.values keeps track of the latest input values.
• The submit button triggers form submission when clicked.
Using Formik handleChange, form values are updated in real time as users type into input fields. The formik.values object stores the latest values.
1console.log("Current form values:", formik.values);
This prints the updated form values every time an input field changes.
Formik handleChange works seamlessly with validation methods like Yup. Form validation helps catch errors before form submission.
1import * as Yup from "yup"; 2 3const validationSchema = Yup.object({ 4 email: Yup.string().email("Invalid email address").required("Required"), 5 username: Yup.string().min(3, "Too short").required("Required"), 6});
By integrating validation, error messages appear when input values are invalid.
Formik tracks validation errors in an errors object. The errors object stores validation messages for each input field.
1{formik.errors.username && <div>{formik.errors.username}</div>} 2{formik.errors.email && <div>{formik.errors.email}</div>}
When validation fails, the error message displays beneath the corresponding input field.
To enable validation, pass a validate function or a Yup schema to Formik.
1const validate = (values) => { 2 let errors = {}; 3 if (!values.email) { 4 errors.email = "Email is required"; 5 } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$/i.test(values.email)) { 6 errors.email = "Invalid email address"; 7 } 8 return errors; 9};
This function returns errors when form values are invalid.
Formik simplifies the form submission process with an onsubmit function. The onsubmit function runs when the submit button is clicked.
1const formik = useFormik({ 2 initialValues: { email: "", username: "" }, 3 validate, 4 onSubmit: (values) => { 5 console.log("Form is submitted with values:", values); 6 }, 7});
Formik prevents form submission if validation errors exist. The submit button only triggers submission when all required fields are valid.
1<button type="submit" disabled={!formik.isValid || formik.isSubmitting}> 2 Submit 3</button>
This ensures that users can only submit the form when validation passes.
Formik automatically binds input fields to the form state.
1<input type="text" name="username" onChange={formik.handleChange} value={formik.values.username} /> 2<input type="email" name="email" onChange={formik.handleChange} value={formik.values.email} />
When a user types into an input field, Formik handleChange updates the corresponding form values.
Formik provides prebuilt form components like Field and ErrorMessage to simplify form handling.
1import { Formik, Form, Field, ErrorMessage } from "formik"; 2 3<Formik 4 initialValues={{ email: "" }} 5 validationSchema={validationSchema} 6 onSubmit={(values) => console.log(values)} 7> 8 <Form> 9 <Field type="email" name="email" /> 10 <ErrorMessage name="email" /> 11 <button type="submit">Submit</button> 12 </Form> 13</Formik>;
Using formik components makes form handling more concise.
Formik’s context API allows multiple components to access form state.
1import { useFormikContext } from "formik"; 2 3const SubmitButton = () => { 4 const { isValid, isSubmitting } = useFormikContext(); 5 return <button type="submit" disabled={!isValid || isSubmitting}>Submit</button>; 6};
This component dynamically updates the submit button based on form validation.
For dynamic forms, Formik handleChange can manage multiple input fields efficiently.
1{fields.map((field, index) => ( 2 <input key={index} name={field.name} onChange={formik.handleChange} value={formik.values[field.name]} /> 3))}
This creates a flexible form that adapts to different input fields.
Formik handleChange makes form handling easier in React. It updates input values, manages errors, and improves form submission.
Using Formik handleChange reduces repetitive code and keeps forms structured. It works well with validation methods and error handling, making forms more reliable.
By adding Formik to your project, you can manage forms with less effort. It helps create smoother user experiences and keeps your code clean.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.