Search code examples
reactjsantdtimepickerant-design-pro

Get reference to a antd time picker and store its value to state variable


I need to get the value that user selected in the time picker to store in a state. In the antd timepicker document I couldn't a reference parameter.

Code:

const format = "HH:mm";

export default function MyTimePicker() {
  const [mytime, setTime] = useState("00:00");

  const handleChange = (e) => {
    setTime(e.targe.value);
    console.log(mytime);
  };

  return (
    <TimePicker
      defaultValue={moment("12:08", format)}
      format={format}
      onChange={handleChange}
    />
  );
}

It shows

Cannot read property 'value' of undefined

The Docs does only have onSelect and onChange but how to get the selected values?


Solution

  • Use onOk when you need to update state only when user click Ok button. Otherwise use onChange or onSelect

      const [timeString, setTimeString] = useState('');
    
      return (
        <TimePicker
          onOk={(time) => {
            setTimeString(timeString);
            console.log(time);
            console.log(timeString);
          }}
        />
      );

    In docs https://ant.design/components/time-picker/ looks like onOk is not presented but you can find onOk description here https://ant.design/components/date-picker/#RangePicker

    When u use onChange you should use handle function with parameters: (time, timeString)