Search code examples
reactjsdatepickerantd

How to clear Datepicker value in Antd Form?


If trigger button inside same Form.Item with Datepicker it works, but if button is outside datepicker does not clear.

I basicly try to clear Datepicker after submit.

It's strange, I could not understand it's antd bug or am I missing something else?

 <Form
    form={form}
    name="advanced_assessment_form"
    onFinish={() => setIsClear(!isClear);}
  >
    <Form.Item
      name="field"
      rules={[
        {
          required: true,
          message: "Input something!"
        }
      ]}
    >
      <DatePicker
        name="datepicker"
        onChange={(val) => {
          setResponseDate(val);
        }}
        value={isClear ? null : responseDate}
      />
      {/* This Button works! */}
      {/* <Button htmlType="submit" onClick={onButton}>
        {" "}
        Clear Datepicker{" "}
      </Button> */}
    </Form.Item>
    <Form.Item>
      {/* This Button does not work */}
      <Button htmlType="submit" onClick={onButton}>
        {" "}
        Clear Datepicker{" "}
      </Button>
    </Form.Item>
  </Form>

here sandbox code : CodeSandbox


Solution

  • I've found solution on antd Form API.

    Just calling below function helps to clear all field.

    form.resetFields();
    

    if you want to set value to a specific field;

    form.setFieldsValue({field: '01/01/2021/, 'DD/MM/YYYY')})
    

    Cheer's