简体   繁体   中英

React js multiple instances of date picker

I am having problem updating the date on react-datepicker if I use multiple instances of datepicker.

Date picker Component:

<DatePicker
  selected={this.state.from}
  onChange={this.changeDate.bind(this)}
/>

On change handler:

changeDate(date) {
    this.setState({
        from : date
    });
}

This seems to work fine if i am using only one instance, but when I add more than one instances, I have to create separate onchange handler for each of the newly created date picker component. What I am looking for is a way to write just a single onchange handler function and handle change events for multiple instances of datepicker in that same function.

You can have a object field state to store each date value in property

this.state = {
    fields: {}
}

handleDateChange = (dateName, dateValue) => {
    this.setState({
        fields: {
            ...this.fields,
            [dateName]: dateValue
        }
    })
}

// IN RENDER
<ReactDatepicker 
    value={this.fields["dateStart"]}
    onChange={(value) => handleDateChange("dateStart", value)}
/>

You can have onChange Handler like that with two argument dateName and dateValue

//in state
 this.state = {
  startDate: moment(),
  endDate: moment(),
}

//My onChange handler function    
handleDateChange(dateName, dateValue) {
    let { startDate, endDate } = this.state;
    if (dateName === 'startDateTime') {
      startDate = dateValue;
    } else {
      endDate = dateValue;
    }
    this.setState({
      startDate,
      endDate,
    });
  }

// Date Picker component
<DatePicker
    id="start-date-time"
    name="startDateTime"
    className="form-control"
    selected={this.state.startDate}
    value={this.state.startDate}
    onChange={date => this.handleDateChange('startDateTime', date)}
    showTimeSelect
    timeFormat="HH:mm"
    timeIntervals={15}
    dateFormat="YYYY-MM-DD, h:mm a"
    timeCaption="time"
  />
//other use of Date picker
<DatePicker


 id="end-date-time"
  name="endDateTime"
  className="form-control"
  selected={this.state.endDate}
  value={this.state.endDate}
  onChange={date => this.handleDateChange('endDateTime', date)}
  placeholderText="choose end date of event"
  isClearable={true}
  showTimeSelect
  timeFormat="HH:mm"
  timeIntervals={15}
  dateFormat="YYYY-MM-DD, h:mm a"
  timeCaption="time"
/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM