简体   繁体   中英

react-select inside react-dates doesn't update select value

I'm using react-dates for a simple birthday picker. I'm using the renderMonthElement prop to render 2 selects on top of the datepicker for months and years:

在此处输入图像描述

Whenever I select a month, the calendar updates correctly however the value shown in the react-select component doesn't update.

My Select looks like this:

<Select
        placeholder="Monat"
        styles={{ indicatorSeparator: () => {}, ...customStyles }}
        options={months}
        filterOption={createFilter(filterConfig)}
        name="months"
        value={bdaymonth}
        className="monthSelect"
        onChange={optionSelected => {
          onMonthSelect(month, optionSelected.label)
          setBdayMonth(optionSelected.label)
        }}
      />

as soon as I take it out of the renderMonthElement , it works perfectly fine by either using bdaymonth from state or just directly with months.label

I thought it might have something to do with the SingleDatePicker being rendered in a Portal but even if I render it inline, the issue persists.

Here is the complete code of my renderMonthElement (pretty much stolen from https://stackoverflow.com/a/57666932/6118046 ):

const renderMonthElement = ({ month, onMonthSelect, onYearSelect }) => {
    let i
    let years = []
    for (i = moment().year() - 16; i >= moment().year() - 100; i--) {
      years.push(
        <option value={i} key={`year-${i}`}>
          {i}
        </option>
      )
    }

    const months = moment.months().map((label, value) => {
      return { value: value, label: label }
    })

    return (
      <BdaySelect>
        <div>
          <Select
            placeholder="Monat"
            styles={{ indicatorSeparator: () => {}, ...customStyles }}
            options={months}
            filterOption={createFilter(filterConfig)}
            name="months"
            value={bdaymonth}
            className="landSelect"
            onChange={optionSelected => {
              onMonthSelect(month, optionSelected.label)
              setBdayMonth(optionSelected.label)
            }}
          />
        </div>
        <div>
          <select
            value={month.year()}
            onChange={e => onYearSelect(month, e.target.value)}
          >
            {years}
          </select>
        </div>
      </BdaySelect>
    )
  }

Got it working by changing the value of the Select to

value={months.filter(function(month) {
  return month.label === bdaymonth;
})}

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