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

时光怂恿深爱的人放手 提交于 2020-06-15 04:26:08

问题


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>
  );
}

回答1:


Please take a look at the Controller doc: https://react-hook-form.com/api/#Controller

which we are maintaining a codesandbox example for hosting most the external components UI libs' implementations: https://codesandbox.io/s/react-hook-form-controller-079xx

<Controller
  as={ReactDatePicker}
  control={control}
  valueName="selected" // DateSelect value's name is selected
  onChange={([selected]) => selected}
  name="ReactDatepicker"
  className="input"
  placeholderText="Select date"
/>


来源:https://stackoverflow.com/questions/60864610/is-it-possible-to-use-react-datepicker-with-react-hooks-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!