ReactHustle

How to Integrate MUI React DatePicker with Formik (Typescript)

Jasser Mark Arioste

Jasser Mark Arioste

How to Integrate MUI React DatePicker with Formik (Typescript)

Hello, hustlers! In this tutorial, you'll learn how to integrate MUI React DatePicker with Formik. We'll also use Typescript throughout this tutorial.

Integrating MUI DatePicker with Formik #

I recently had to integrate MUI DatePicker with Formik. I had trouble creating a custom reusable component <FormikDatePicker/>  that inherits the Props of  <DatePicker/>.

I eventually figured it out by creating a generic component and here's how I did it.

Step 0 - Setup #

I assume you already have the @mui/x-date-pickers package installed. If not, go ahead and install it by running the command:

yarn add @mui/x-date-pickers

We'll also use dayjs as the date solution so let's install it as well.

yarn add dayjs

Step 1 - Defining the FormikDatePickerProps #

Next, let's define the FormikDatePickerProps. We'll have to make it generic since DatePickerProps is generic as well. First, create the file components/FormikDatePicker.tsx and copy the code below:

// components/FormikDatePicker.tsx
import { DatePicker, DatePickerProps } from "@mui/x-date-pickers/DatePicker";
type Props<TInputDate, TDate> = {
  name: string;
} & Omit<DatePickerProps<TInputDate, TDate>, "onChange" | "value">;
12345

Explanation:

We define the Props with a name property since we'll be using useField and setFieldValue later on.

We omit onChange and value from the DatePickerProps for the same exact reason.

Lastly, we just pass the generic types to DatePickerProps. This way, we retain the DatePickerProps as much as possible and customize only what we need.

Step 2 - Creating a Generic Component #

Next, let's create a generic component that uses the generic Props. If you want to know more about generic components in typescript, check out this Guide by React Typescript CheatSheet.

// components/FormikDatePicker.tsx
import { DatePicker, DatePickerProps } from "@mui/x-date-pickers/DatePicker";
...
const FormikDatePicker = <TInputDate, TDate = TInputDate>(props: Props<TInputDate, TDate>) => {
  const { name, ...restProps } = props;
  return (
    <DatePicker
      {...restProps}
      value={null}
      onChange={(val) => console.log(val)}
    />
  );
};
export default FormikDatePicker;
1234567891011121314

Step 3 - Integrating Formik #

Next, let's integrate Formik by using useField and setFieldValue. I think this is the cleanest approach when integrating formik into any component.  We also modified the value and onChange props:

// components/FormikDatePicker.tsx
import { DatePicker, DatePickerProps } from "@mui/x-date-pickers/DatePicker";
import { useField, useFormikContext } from "formik";
import React from "react";
type Props<TInputDate, TDate> = {
  name: string;
} & Omit<DatePickerProps<TInputDate, TDate>, "onChange" | "value">;
const FormikDatePicker = <TInputDate, TDate = TInputDate>(
  props: Props<TInputDate, TDate>
) => {
  const { name, ...restProps } = props;
  const [field] = useField(name);
  const { setFieldValue } = useFormikContext();
  return (
    <DatePicker
      {...restProps}
      value={field.value ?? null}
      onChange={(val) => setFieldValue(name, val)}
    />
  );
};
123456789101112131415161718192021

Step 4 - Usage #

To use the component we'll have to use the <Formik/> provider to give us the context. Also, don't forget to wrap your component with the <LocalizationProvider/>.

// pages/index.tsx
import { Button, TextField } from "@mui/material";
import FormikDatePicker from "components/FormikDatePicker";
import { Formik, Form } from "formik";
import { NextPage } from "next";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import { LocalizationProvider } from "@mui/x-date-pickers";
...
const HomePage: NextPage = () => {
  return (
    <LocalizationProvider dateAdapter={AdapterDayjs}>
      <Container maxWidth="xs">
        <Formik
          initialValues={{
            start_date: null,
          }}
          onSubmit={(values) => console.log(JSON.stringify(values, null, 4))}
        >
          <Form>
            <Stack gap={2} my={10}>
              <Typography variant="h3" fontWeight={700}>
                My Form
              </Typography>
              <FormikDatePicker
                name="start_date"
                renderInput={(params) => (
                  <TextField {...params} label="Start date" />
                )}
              />
              <Button type="submit" variant="outlined" color="primary">
                Submit
              </Button>
            </Stack>
          </Form>
        </Formik>
      </Container>
    </LocalizationProvider>
  );
};

export default HomePage;
1234567891011121314151617181920212223242526272829303132333435363738394041

Conclusion #

We learned how to integrate MUI React DatePicker with Formik in Typescript by creating a generic component that uses setFieldValue and useField.

If you like this tutorial, please leave a like or share this article. For future tutorials like this, please subscribe to our newsletter.

Credits: Image by Leonhard Niederwimmer from Pixabay

Share this post!

Related Posts

Disclaimer

This content may contain links to products, software and services. Please assume all such links are affiliate links which may result in my earning commissions and fees.
As an Amazon Associate, I earn from qualifying purchases. This means that whenever you buy a product on Amazon from a link on our site, we receive a small percentage of its price at no extra cost to you. This helps us continue to provide valuable content and reviews to you. Thank you for your support!
Donate to ReactHustle