Search code examples
reactjsantdreact-hook-form

Antd RangePicker Component with React Hook Form


I currently have a react-hook-form managed form that I've added an antd RangePicker to. I'm having issues with updates to the RangePicker getting passed to the form object. Currently, the default values are passing fine but it's not taking any changes.

OnChange events seem to be being handled by the standard Controller method with the other field types (Input, etc.). My guess is I have to write something custom here but I'm not sure. Thanks in advance for any help.

Here is my current antd DatePicker that is being managed with react-hook-forms Controller method.

EDIT: Updated my code to use the render method in react-hook-form v6+ as opposed to the as method. I also noticed if I don't pass any defaultValue then the RangePicker accepts and passes both the start and end dates fine. But when I set the defaultValue it always returns the default start date twice.

<Controller
    name="materialarrivalpickup"
    control={control}
    defaultValue={[
        moment(user.project.projectmaterialarrival),
        moment(user.project.projectmaterialpickup),
    ]}
    rules={{ required: true }}
    render={(props) => (
        <RangePicker
        {...props}
        format="MM/DD/YYYY"
        onChange={(e) => {
            props.onChange(e);
            console.log("Range Picker " + e);
        }}
        />
    )}
/>

Solution

  • Figured this out. Apparently, react-hook-form was properly passing the RangePicker changes to my form object I just couldn't tell based on the log.

    When I update the picker the Moment object (two dates) wasn't looking updated in the log produced by react-hook-form watch() (both look like they're 3/3/2020).

    Log pre

    But when I expand the Moment object I'm getting my updated dates (3/3/2020 and 3/5/2020).

    Log post

    I'll leave my working RangePicker + react-hook-form code here for anyone else that needs it.

    <Controller
        name="materialarrivalpickup"
        style={{ marginBottom: "8px" }}
        control={control}
        defaultValue={[
        moment(user.project.projectmaterialarrival),
        moment(user.project.projectmaterialpickup),
        ]}
        rules={{ required: true }}
        render={(props) => (
        <RangePicker
            {...props}
            format="MM/DD/YYYY"
            onChange={(e) => {
            props.onChange(e);
            console.log("Range Picker: " + e);
            }}
        />
        )}
        />