set a value in react-datepicker dynamically in react



I used react-datepicker. I tried to set the value of react-datepicker from the value which I received as props from another component but either it didn’t show the value or it shows a blank page by saying ‘wrong time format’.

Datepicker code:

this.state = {
  venue_id: props.location.state ? props.location.state.venue_id : null,
  event_start_date: props.location.state ? props.location.state.date : null,
}

<DatePicker
  selected={this.state.event_start_date}
  onChange={this.handleStartDate}
  minDate={new Date()}
  dateFormat="MM/dd/yyyy"
/>

I checked the console and found that props were received successfully by the date picker component but still I wasn’t able to set the value.

Answer

It looks like the event_start_date is not a proper type for selected. There are 2 possibilities:

  1. When “props.location.state” returns false, event_start_date is null, which may cause the error.

  2. When “props.location.state” returns true, event_start_date takes the value of props.location.state.date, but it maybe not a Date type. You can use typeof event_start_date.getMonth === 'function' to find out.



Source: stackoverflow