Search code examples
cssreactjsformsreact-hook-formflatpickr

How to manually re-render component using react-hook-form when validation errors are updated


facing challenges making validation classes to reflect automatically on custom datepicker Flatpickr using React-Hook-Forms,

const { register, handleSubmit, errors, control } = useForm({
  mode: 'onChange'
})

<FormGroup>
  <Controller
    name="dateControl"
    control={control}
    defaultValue={null}
    rules={{ required: true }}
    render={({ value, onChange }) => (
      <Flatpickr
        value={value}
        onChange={onChange}
        id="hf-picker"
        options={{
          altInput: true,
          altFormat: 'F j, Y',
          dateFormat: 'Y-m-d',
          altInputClass: classnames(
            'form-control flatpickr-input',
            {
              'is-invalid': errors.dateControl && true
            }
          )
        }}
      />
    )}
  />
</FormGroup>

After troubleshooting, I realize everything works except that component fails to re-render whenever the validation errors are updated by react-hooks-form, is there anyway I can force a manual re-render instead, thanks


Solution

  • I think this has nothing to do with RHF, but somehow the options prop of the <Flatpickr /> component isn't updated when the config changes.

    I'm assuming your using the react-flatpickr package - what you could do is simply pass the key prop to this component and setting it to the errors object of that control. This will force a re-render every time the errors of that form control change.

    const isNotEmpty = (array) => array?.length > 0 || "Required";
    
    <Controller
      name="dateControl"
      control={control}
      defaultValue={null}
      rules={{ validate: isNotEmpty }}
      render={({ value, onChange }) => (
        <>
          <Flatpickr
            key={errors.dateControl}
            value={value}
            onChange={onChange}
            id="hf-picker"
            options={{
              altInput: true,
              altFormat: "F j, Y",
              dateFormat: "Y-m-d",
              altInputClass: classnames("form-control flatpickr-input", {
                "is-invalid": !!errors.dateControl
              })
            }}
          />
          {errors.dateControl && <p>{errors.dateControl.message}</p>}
        </>
      )}
    />
    

    Edit React Hook Form - Basic (forked)