How to set custom date to DatePicker of react-datepicker using MomentJS?

扶醉桌前 提交于 2019-12-11 05:26:15

问题


I have stored dates in database. I can fetch dates successfully. But when it comes to set any particular date to DatePicker of react-datepicker, I couldn't set that date.

Here is code that I have used for fetching dates and setting state with the value of date.

loadAllEvents() {
    axios({
        method: 'POST',
        url: '/api/Account/SelectAllDatesFromDb',
        contentType: 'application/json',
        data: {},
    }).then(function (response) {
        if(response!=null){     
            this.setState({
                eventList: response.data
            });
            this.updateAllDates();
        }
        else {
            this.setState({
                eventList: []
            });
        }

    }.bind(this))
        .catch(function (error) {
            console.log(error);
        });
}

UpdateAllDates() function for converting dates using MomentJs

updateAllDates() {
        for (var i = 0; i < this.state.eventList.length; i++) {
            var items = this.state.eventList;
            items[i].event_date = moment(this.state.eventList[i].event_date).format("DD/MM/YYYY");
            this.setState({ eventList: items });    
        }
    }

After getting dates, now I try to set date to datepicker and try to set selected parameter. Here is code:

<InputGroup>
  <DatePicker
    className="form-control"
    dateFormat="dd/MM/yyyy"
    maxDate={new Date()}
    isClearable={true}
    selected={this.state.eventList[0].event_date}
    onChange={this.handleChange}
    disabled={this.state.eventDateBox}
    showYearDropdown
    showMonthDropdown
  />

When I runs code I get error - TypeError: Cannot read property 'event_date' of undefined:

Where am I making mistake? Is there any other way of setting a date to DateTimePicker with default/custom date?

来源:https://stackoverflow.com/questions/57592396/how-to-set-custom-date-to-datepicker-of-react-datepicker-using-momentjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!