Disable specific days in material ui calendar in React
in the updated API it's the "disablePast" property.
check https://material-ui-pickers.dev/api/DatePicker
Consider this above code code is cutted (demo code is inside a component)
disableWeekends(date) {
/* date interdites french format dd/mm for all year !
01/01
01/05
08/08
14/07
15/08
01/11
11/11
25/12
replace date.getFullYear() by the desired year otherwise
*/
// in the following array format is us month are starting from 0 till 11
const dateInterditesRaw = [
new Date(date.getFullYear(),0,1),
new Date(date.getFullYear(),4,1),
new Date(date.getFullYear(),7,8),
new Date(date.getFullYear(),6,14),
new Date(date.getFullYear(),7,15),
new Date(date.getFullYear(),10,1),
new Date(date.getFullYear(),10,11),
new Date(date.getFullYear(),11,25),
];
/* make a new array with the getTime() without it date comparaison are
never true */
const dateInterdites = dateInterditesRaw.map((arrVal) => {return
arrVal.getTime()});
/*exclude all sunday and use the includes array method to check if the
date.getTime() value is
in the array dateInterdites */
return date.getDay() === 0 || dateInterdites.includes(date.getTime());
}
render() {
return(
<DatePicker
floatingLabelText="Jour de la visite"
value={this.props.dateVisite}
shouldDisableDate={this.disableWeekends}
onChange={this.handleChangeDateVisit}
/>
);
}
}
Here is the sample code that needed to be added. You can refer this link for more details - https://material-ui.com/components/pickers/#date-time-pickers
You can add condition according to your need in order to disable date.
import React from 'react';
import DatePicker from 'material-ui/DatePicker';
function disableWeekends(date) {
return date.getDay() === 0 || date.getDay() === 6;
}
function disableRandomDates() {
return Math.random() > 0.7;
}
/**
* `DatePicker` can disable specific dates based on the return value of a callback.
*/
const DatePickerExampleDisableDates = () => (
<div>
<DatePicker hintText="Weekends Disabled" shouldDisableDate={disableWeekends} />
<DatePicker hintText="Random Dates Disabled" shouldDisableDate={disableRandomDates} />
</div>
);
export default DatePickerExampleDisableDates;
I tried to filter the days I had as an array of days with the steps below:
converted strings into a Date object.
converted the Date objects into timeStamp for comparison.
compare timeStamps plus the weekends with all the dates we have in our calendar.
const disableBookedDays = (date) => { const convertedIntoDateObject = bookedDates.map((bookedDate) => { return new Date(bookedDate).getTime(); }); return date.getDay() === 0 || date.getDay() === 6 || convertedIntoDateObject.includes(date.getTime()); };