Search code examples
javascriptreactjsreact-hook-formreact-datepicker

How to make datepicker work with react hook form?


I have a short code below, the date picker works fine, it changes when I select other dates. But i can't figure it out why it always fail in required validation even I already select a date.

<Controller
    control={control}
    name="disclosureDate"
    rules={{ required: 'This field is required' }}
    errors={errors.disclosureDate}
    value={disclosureDate}
    render={({ field }) => (
      <InputDate
        className="mb-px-8"
        onChange={(value) => setDisclosureDate(value)}
        value={disclosureDate}
      />
    )}
/>

I've been following of these links, but I can't make it work in my end.

react-hook-link-Controllers

stackoverflow-link

(by the way, there are other validations aside from required, for demonstration purposes only)


Solution

  • I don't think you are using the Controller correctly. You should use the value and onChange it provides in the render prop, try -

    <Controller
        control={control}
        name="disclosureDate"
        rules={{ required: 'This field is required' }}
        errors={errors.disclosureDate}
        value={disclosureDate}
        render={({ value, onChange }) => (
          <InputDate
            className="mb-px-8"
            onChange={onChange}
            value={value}
          />
        )}
    />