How to use react-datepicker with React hooks forms?

Sometimes, we want to use react-datepicker with React hooks forms.

In this article, we’ll look at how to use react-datepicker with React hooks forms.

How to use react-datepicker with React hooks forms?

To use react-datepicker with React hooks forms, we can wrap it in the Controller component.

For instance, we write:

import React from "react";
import { Controller, useForm } from "react-hook-form";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";

export default function App() {
  const {
    handleSubmit,
    watch,
    control,
    formState: { errors }
  } = useForm();
  const onSubmit = (data) => console.log(data);

  console.log(watch("dateInput"));

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Controller
        control={control}
        name="dateInput"
        render={({ field }) => (
          <DatePicker
            placeholderText="Select date"
            onChange={(date) => field.onChange(date)}
            selected={field.value}
          />
        )}
      />
      {errors.dateInput && <span>This field is required</span>}

      <input type="submit" />
    </form>
  );
}

We call the useForm hook to return an object with various properties we use to add the date picker into the form.

Next, we add the Controller component in the form.

We set the control prop to control and we set the render prop to a function that renders the DatePicker component.

Then we set onChange to a function that calls field.onChange to set the value of the date picker.

And we render the value by setting the selected prop to field.value.

Conclusion

To use react-datepicker with React hooks forms, we can wrap it in the Controller component.