Search code examples
javascriptreactjsdatepickermomentjsantd

Antd <DatePicker/> if value props is set, and click will be infinite loop


I want to set value in value props <DatePicker>. But if i set value, and if i click the date picker, calendar will be infinite loop to the future. i have use DefaultValue and value props, but produce same error

import React from "react";
import "./index.css";
import type { DatePickerProps } from "antd";
import { DatePicker, Space } from "antd";
import moment from "moment";

const onChange: DatePickerProps["onChange"] = (date, dateString) => {
  console.log(date, dateString);
};
const day = moment();
const format = "DD.MM.YYYY";

const App: React.FC = () => (
  <Space direction="vertical">
    <DatePicker
      onChange={onChange}
      format={format}
      defaultValue={moment(day)}
    />
  </Space>
);

export default App;

You can try here SANBOX

and the picture is here PICTURE

i have use DefaultValue and value props, but produce same error. i have delete DefaultValue and value props and calendar is normal, but i cannot set value from beginning


Solution

  • As per the documentation and the below error from the defaultValue when using moment js shows that the accepted format is day js

    Type 'string' is not assignable to type 'Dayjs'.

    To resolve above issue of showing date , follow below steps

    1. Import dayjs
    2. Using defaultvalue attribute, assign current date using dayjs

    import React from "react";
    import "./index.css";
    import type { DatePickerProps } from "antd";
    import { DatePicker, Space } from "antd";
    //import moment from "moment";
    import dayjs from "dayjs";
    
    const onChange: DatePickerProps["onChange"] = (date, dateString) => {
      console.log(date, dateString);
    };
    
    const format = "DD.MM.YYYY";
    
    const App: React.FC = () => (
      <Space direction="vertical">
        <DatePicker onChange={onChange} format={format} defaultValue={dayjs()} />
      </Space>
    );
    
    export default App;

    Updated the codesandbox for your reference - https://codesandbox.io/s/basic-antd-5-1-7-forked-b87dbv?file=/demo.tsx

    Documentation link for reference- https://ant.design/components/date-picker