Formik is a widely used React library for building forms and managing form state. Typically, Formik employs the useFormik hook or the <Formik> component to manage form input states such as values, errors, and touched, while providing handleChange and handleBlur methods to handle changes and blur events for input fields. If you wish to customize the onChange or onBlur event handlers, you can follow the examples below.
First, here is the standard approach to using Formik, where handleChange and handleBlur automatically handle changes and blur events for form inputs:
jsximport { Formik, Form, Field } from 'formik'; function MyForm() { return ( <Formik initialValues={{ myField: '' }} onSubmit={(values) => { // Actions to perform on form submission }} > {({ handleChange, handleBlur, handleSubmit, values }) => ( <Form onSubmit={handleSubmit}> <Field name="myField" onChange={handleChange} onBlur={handleBlur} value={values.myField} /> {/* Other form elements */} </Form> )} </Formik> ); }
To customize the onChange or onBlur events, you can directly implement these handlers on the Field component or on <input>, <select>, and <textarea> elements. Here is an example demonstrating how to customize these events:
jsximport { Formik, Form, Field } from 'formik'; function MyForm() { return ( <Formik initialValues={{ myField: '' }} onSubmit={(values) => { // Actions to perform on form submission }} > {({ handleChange, handleBlur, handleSubmit, values, setFieldValue, setFieldTouched }) => { // Custom onChange handler const customOnChange = (e) => { const { name, value } = e.target; // Add custom logic here console.log('Custom onChange for', name, 'with value', value); // Invoke Formik's handleChange to update the value handleChange(e); }; // Custom onBlur handler const customOnBlur = (e) => { const { name } = e.target; // Add custom logic here console.log('Custom onBlur for', name); // Invoke Formik's handleBlur to set the touched state handleBlur(e); }; return ( <Form onSubmit={handleSubmit}> <Field name="myField" onChange={customOnChange} onBlur={customOnBlur} value={values.myField} /> {/* Other form elements */} </Form> ); }} </Formik> ); }
In the above example, customOnChange and customOnBlur functions are used to add custom logic, and they invoke Formik's handleChange and handleBlur to ensure the form state is correctly updated. You can incorporate any logic in these custom handlers, such as field validation or input value formatting.