In this article, we will see how to use react datepicker with formik for date selection and form submission.

Before you begin, click on the following links to get a high-level understanding of the react datepicker and formik visit the following links.

Let’s get started by installing the formik and react-datepicker. Use the following command to install the dependencies

npm install react-datepicker formik

Define the form component and integrates both datepicker and formik

import React from 'react';
import { Formik, Field, Form, ErrorMessage } from 'formik';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';

const MyForm = () => {
  const initialValues = {
    date: null,
  };

  const handleSubmit = (values) => {
    // Handle form submission
    console.log(values);
  };

  return (
    <Formik initialValues={initialValues} onSubmit={handleSubmit}>
      <Form>
        <div>
          <label htmlFor="date">Date:</label>
          <Field name="date">
            {({ field, form }) => (
              <DatePicker
                id="date"
                {...field}
                selected={field.value}
                onChange={(date) => form.setFieldValue(field.name, date)}
              />
            )}
          </Field>
          <ErrorMessage name="date" component="div" />
        </div>
        <button type="submit">Submit</button>
      </Form>
    </Formik>
  );
};

Finally, render the <MyForm/> component

function App() {
  return (
    <div className="App">
      <h1>React Datepicker with Formik Form</h1>
      <MyForm />
    </div>
  );
}

export default App;

Explanation:

In the above example, we import the necessary components such as Formik, Field, Form, ErrorMessage from the formik library.

We wrapped our <Form/> component inside the <Formik/> and inside the Form component, we use the Field component from Formik to handle the form field. We specify the name of the field as "date" and within the Field component, we render the DatePicker component from React Datepicker.

The selected prop of the DatePicker component is set to field.value, which connects it to Formik’s form state. The onChange callback is used to update Formik’s form state when the date changes.

Finally, we render the ErrorMessage component from Formik to display any validation errors for the date field.

Categorized in:

Tagged in: