Search code examples
javascriptreactjsecmascript-6react-datepicker

Is there any way to keep date selected on changing Month or Year of the react-datepicker in reactjs?


Currently, in the react-datepicker, I am using Month selector and Year selector for DOB in guest detail form.

What happening is:- The selected date is highlighted on the calendar, which is fine.

What I need to implement:- When I change Month/Year on the calendar, I want to update the selected date to the same date as it was before with updated Month/Year.

Please help me with any possibility.

I am not able to find the solution for this.

The following code is what I am using for current react-datepicker:

    <DatePicker
        className="date-field ub-l"
        openToDate={new Date("1993/09/28")}
        selected={this.state.date}
        onSelect={this.handleChange}
        onChange={this.handleChange} //only when value has changed
        maxDate={new Date()}
        placeholderText={this.props.placeholder}
        disabledKeyboardNavigation={true}
        showMonthDropdown={true}
        showYearDropdown={true}
        name={this.props.name}
        disabledNavigation
        inputProps={{readOnly: true}}
        dropdownMode="select"
        autocomplete={false}
    />

If I change Month/Year is it possible to update the selected date with the updated Month/Year automatically before selecting any date?


Solution

  • You're looking for the adjustDateOnChange prop. It automatically does what you're looking for

    <DatePicker
      selected={selectedDate}
      onChange={date => changeDate(date)}
      dropdownMode="select"
      showMonthDropdown
      showYearDropdown
      adjustDateOnChange
    />
    

    Codesandbox