Search code examples
javascriptreactjsdatepickerreact-datepicker

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.


Solution

  • 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)}
    />