Home > database >  How can I disable specific select options if given condition is true?
How can I disable specific select options if given condition is true?

Time:10-07

I am using ant design select field with options of months. I have an array of 12 months of a year and I am mapping it through and displaying it as dropdown selectable options. I want to disable all previous months before present month. For example, If present month is October, I want to disable all of previous months before October, so user won't be able to select those months. This is how it looks like on screen and below is my code, any help would be greatly appreciated.

const monthData = ["JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"];

<Select
getPopupContainer={(trigger) =>  return trigger}}
autoClearSearchValue={true}
bordered={false}
showSearch
placeholder="Select Month"
optionFilterProp="children"
>
{monthData.map((month) => (<Option value={month} {/*disabled = {}*/}>{month}</Option>))}
</Select>

CodePudding user response:

First get the index of current month using built-in Date:

const currentMonthIndex = new Date().getMonth();

Now you can enable/disable the Option components using map:

{monthData.map((month, index) => (<Option value={month} disabled={index < currentMonthIndex}>{month}</Option>))}
  • Related