How do I disable future dates in react js or Vanilla or JavaScript

57 Views Asked by At

I have two drop down

  1. It only has years which is restricted to last 7 years from present year (Working fine)
  2. It only has months which should show the months till present month only

for Example if we today date is (15 march 2023) then the drop down should show Year - 2023 and Month drop down should show value from Jan to March (Future months should be restricted) (but now it is showing all months)

enter image description here

Now the code for year is as follow

  const minAppDate = new Date(
  new Date().getFullYear() - 7,
  new Date().getMonth(),
  new Date().getDate()
);
const maxAppDate = new Date(
  new Date().getFullYear(),
  new Date().getMonth() - 1
);
    const range = (start, stop, step = 1) => {
  if (typeof stop === 'undefined') {
    // One param defined
    stop = start;
    start = 0;
  }

  if ((step > 0 && start >= stop) || (step < 0 && start <= stop)) {
    return [];
  }

  const result = [];
  for (let i = start; step > 0 ? i < stop : i > stop; i += step) {
    result.push(i);
  }

  return result;
};
const years = range(minAppDate.getFullYear(), maxAppDate.getFullYear() + 1).map(
  year => ({
    label: year,
    value: year
  })
);

the value is getting stored in Year

similary i am doing for month

months: [
    'Jan',
    'Feb',
    'Mar',
    'Apr',
    'May',
    'Jun',
    'Jul',
    'Aug',
    'Sep',
    'Oct',
    'Nov',
    'Dec'
  ]

const months = months.map((month, index) => ({
  label: month,
  value: index < 9 ? '0' + (index + 1) : index + 1
}));

after that i am passing the values in DropDown options

<Dropdown
              required
              id='year'
              options={years}
              label='Year'
              name='year'
              value={values.year}
              onChange={handleChange}
            />

so i want to send the option before only can any one let me know what i am doing wrong

0

There are 0 best solutions below