1

I am using react-datetime inside a react-hook-form

enter image description here

I want the user to easily set the time to current time using a button Immediate. Instead of selecting the current time manually.

I am trying the below


const [currentDateTime, setcurrentDateTime] = useState(null);
<Controller
    name="resetDateTime"
    control={control}
    required
    render={({ field }) => (
        <Datetime
            onChange={setcurrentDateTime}
            inputProps={{
                placeholder: "MM-DD-YYYY HH:mm",
            }}
            value={currentDateTime}
            viewMode="time"
        />
    )}
/>
<Button color="primary" className="ml-1" onClick={() => setcurrentDateTime(moment())}>
    {"Immediate"}
</Button>

The problem is onSubmit the react-hook-form I get resetDateTime = undefined

How to implement this properly. So I can use the Immediate button and also submit form and get the resetDateTime value

Santhosh
  • 9,965
  • 20
  • 103
  • 243

1 Answers1

1

You're mixing RHF with your local state currentDateTime and are not linking the. field to RHF as you're missing to spread the field object to your <Datetime /> component.

The correct way would be to use RHF's setValue to update your resetDateTime field and get rid of the useState hook.

const { control, handleSubmit, setValue } = useForm();
<Controller
    name="resetDateTime"
    control={control}
    required
    render={({ field }) => (
        <Datetime
            {...field}
            inputProps={{
                placeholder: "MM-DD-YYYY HH:mm",
            }}
            viewMode="time"
        />
    )}
/>

<Button color="primary" className="ml-1" onClick={() => setValue("resetDateTime", moment())}>
    {"Immediate"}
</Button>
knoefel
  • 5,991
  • 3
  • 29
  • 43