react-datetime - Can't edit Date or Time

1.9k views Asked by At

When clicked on the input box and type something valid, input will clear or some random date and time will assign to this input.

It is allowing me to select date or time with mouse. Whenever type, input will clear or assign random values.

<Datetime
  value={moment(date)}
  onChange={(date) => setDate(date)}
  dateFormat="DD/MM/YYYY"
  timeFormat="HH:mm:ss"
  utc={true}
/>

When trying with "defaultValue" instead of "value", this will allow to type date or time but it will not appear the value of "date" which i passed through my react state.

<Datetime
  defaultValue={moment(date)}
  onChange={(date) => setDate(date)}
  dateFormat="DD/MM/YYYY"
  timeFormat="HH:mm:ss"
  utc={true}
/>

Image Reference

date picker

  • Version of react-datetime -> "react-datetime": "^2.16.3",
1

There are 1 answers

0
Dave On

Your top example is correct. You've build a 'controlled component'. The date is stored in your date state variable. Any time a change occurs that value is updated and the element will be re-rendered. When the element renders, it displays the value.

The issue is you're sending the raw user input to the Moment library, and it's returning a weird date/time. You'll need to "fix" the user's input before passing it into Moment and honestly there's no reason to do that much work. I'd hunt around the internet and find a better date/time component. (Also Moment is considered old. People prefer date-fns these days.)

See also: React controlled component