Introduction
Sometimes, when you are building a form using formik, you need to know if there has been a change in any of the fields to execute an action, in my case for example to enable or disable the save button. Many tutorials suggest to compare the initialValues
object with current values
object using lodash
or comparing field by field.
But there is a property in formik called dirty
that saves you all that work and tells you if there was a change in your form, according to the formik documentation:
dirty
property returns true
if values are not deeply equal from initial values, false
otherwise. dirty
is a readonly computed property and should not be mutated directly
Implementation
We create a very simple form with two fields and a sumbit button because we will focus only in the dirty
property, in this we assign initial values to our form supposing that it is an edit form and we want to enable the submit button only when there is a change in some input, in the example we are receiving the dirty
property whose initial value is false and we use it to disable the submit button, in case there are changes the value of the dirty
property will be true, and when denying it the value of the disabled property will be false, therefore the submit button will be enabled.
import React from 'react';
import { Formik, Form, Field } from 'formik';
import * as Yup from 'yup';
const initialValues = {
name: 'John Doe',
email: 'john.doe@example.com'
};
const SimpleForm = () => (
<div>
<Formik
initialValues={initialValues}
// Here you can handle the logic to send the data
onSubmit={(values) => {}}
>
{({ values, handleChange, dirty }) => (
<Form>
<div>
<Field type="text" id="name" name="name" placeholder="name" value={values.name} onChange={handleChange} />
</div>
<div>
<Field type="text" id="email" name="email" placeholder="email" value={values.email} onChange={handleChange} />
</div>
<button type="submit" disabled={!dirty}>
Save
</button>
</Form>
)}
</Formik>
</div>
);
export default SimpleForm;
Conclusion
Using the dirty property you can save a lot of time comparing value by value in formik forms, especially if they are large forms and you only need to know if there was any change in some input no matter what it was.
Top comments (0)