Sometimes, we want to use React-datepicker with a Formik form.
In this article, we’ll look at how to use React-datepicker with a Formik form.
How to use React-date picker with a Formik form?
To use React-date picker with a Formik form, we can create a date picker component that renders the React-datepicker component.
We use the useFormikContext
hook to let us add form validation with Formik to the React-datepicker component.
For instance, we write:
import React from "react";
import { Formik, useField, useFormikContext } from "formik";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
const DatePickerField = ({ ...props }) => {
const { setFieldValue } = useFormikContext();
const [field] = useField(props);
return (
<DatePicker
{...field}
{...props}
selected={(field.value && new Date(field.value)) || null}
onChange={(val) => {
setFieldValue(field.name, val);
}}
/>
);
};
export default function App() {
return (
<div>
<Formik
initialValues={{ date: "" }}
onSubmit={(values, { setSubmitting }) => {
setTimeout(() => {
console.log(JSON.stringify(values, null, 2));
setSubmitting(false);
}, 500);
}}
>
{(props) => {
const { dirty, isSubmitting, handleSubmit, handleReset } = props;
return (
<form onSubmit={handleSubmit}>
<DatePickerField name="date" />
<button
type="button"
className="outline"
onClick={handleReset}
disabled={!dirty || isSubmitting}
>
Reset
</button>
<button type="submit" disabled={isSubmitting}>
Submit
</button>
</form>
);
}}
</Formik>
</div>
);
}
We define the DatePickerField
component that takes the props from the props
object.
In the component, we call useFormikContext
to return an object with the setFieldValue
method.
Then we call the useField
hook with props
to create the field
object which we use to set the selected
state and use the field.name
property to get the field’s name.
We call setFieldValue
to set the field’s value by passing in the field name string and the selected value.
Then to use DatePickerField
in a Formik form, we put it inside the render prop’s return value.
useFormikContext
and useField
returned all the values required to let Formik handle value change and form validation.
We also set initialValues
to an object with the name of the field as the property names.
And we set the name
prop of DatePickerField
to the same value as the property value so validation and the value can be set as the value of the property with the same name.
Conclusion
To use React-date picker with a Formik form, we can create a date picker component that renders the React-datepicker component.
We use the useFormikContext
hook to let us add form validation with Formik to the React-datepicker component.