reactjsreact-datepickerreact-hook-form

Is it possible to use react-datepicker with react hooks forms?


Is it possible to use react-datepicker with react hooks forms? I tried following sample:

https://codesandbox.io/s/awesome-shape-j0747?fontsize=14&hidenavigation=1&theme=dark

But with no luck.

import React, { useState } from "react";
import "./styles.css";
import { useForm } from "react-hook-form";
import { Row, Col, Form, FormGroup, Label, Input, Button } from "reactstrap";
import DatePicker from "react-datepicker";

export default function App() {
  const { register, handleSubmit } = useForm();
  const [startDate, setStartDate] = useState();
  const [result, setResult] = useState();

  const onSearch = event => {
    setResult(event);
  };

  return (
    <div className="App">
      <Form onSubmit={handleSubmit(onSearch)}>
        <Row>
          <Col>
            <FormGroup>
              <Input
                type="number"
                name="account"
                id="account"
                placeholder="AccountId"
                innerRef={register({ required: true, maxLength: 20 })}
              />
            </FormGroup>
          </Col>
        </Row>

        <Row>
          <Col>
            <DatePicker
              innerRef={register}
              name="datetime"
              className={"form-control"}
              selected={startDate}
              onChange={date => setStartDate(date)}
              showTimeSelect
              timeFormat="HH:mm"
              timeIntervals={15}
              timeCaption="time"
              dateFormat="MM-dd-yyyy h:mm"
            />
          </Col>
        </Row>

        <Button>Submit</Button>
      </Form>
      <div>{JSON.stringify(result)}</div>
    </div>
  );
}

Solution

  • With react-hooks-form v7

    Import dependencies:

    import { Controller, useForm } from 'react-hook-form'
    import DatePicker from 'react-datepicker'
    

    Add control to the useForm() hook:

    const { control, register, handleSubmit, ... } = useForm()
    

    Add the Controller and DatePicker component:

     <Controller
        control={control}
        name='date-input'
        render={({ field }) => (
          <DatePicker
            placeholderText='Select date'
            onChange={(date) => field.onChange(date)}
            selected={field.value}
          />
       )}
      />