I would like to disable selected dates in calendar. I dit it, but problem is when I disable date in month may, it will disable it in all months. For example: If I disable day 4th in May it will disable day 4th in all months. I saw also this link: how to disable some dates in react-calendar How can I fix this. Thanks
let disableDates = ''
let date1 = ''
let selectedDays = []
let disable = []
const handleClick = (date) => {
disableDates = new Date(date)
date1=disableDates.getDate()
disable.push(date1)
console.log(disable) //(2) [2, 3]
selectedDays.push(date)
console.log('selectedDays', selectedDays) //(2) [Fri Jun 02..., Sat Jun...]
}
ReactCalendar here:
<ReactCalendar
minDate={new Date()}
// tileDisabled={({date}) => date.getDate()===date1}
tileDisabled={({date}) => disable.includes(date.getDate()) }
onClickDay={handleClick}
/>
That's because you're using the same disable
array to store the disabled dates for all months. To solve, try to separate disable
array for each month:
let disabledDates = {};
const handleClick = (date) => {
const selectedDate = new Date(date);
const month = selectedDate.getMonth();
const disabledMonthDates = disabledDates[month] || [];
const selectedDay = selectedDate.getDate();
if (!disabledMonthDates.includes(selectedDay)) {
disabledMonthDates.push(selectedDay);
} else {
const index = disabledMonthDates.indexOf(selectedDay);
disabledMonthDates.splice(index, 1);
}
disabledDates[month] = disabledMonthDates;
console.log(disabledDates);
};
ReactCalendar:
<ReactCalendar
minDate={new Date()}
tileDisabled={({ date }) =>
disabledDates[date.getMonth()]?.includes(date.getDate())
}
onClickDay={handleClick}
/>