javascriptreactjsmaterial-uimui-x-date-picker

How to disable list of dates in MUI X Date Picker


I want to disable MUI X Date Picker future dates (only selected dates not all future dates)
I am getting array of dates from API which needs to be disabled from date picker.

Assume that below blackoutDates are what i am getting from API. So how to disable those dates ?

Below is my code

const getDisabledDates = () => {
 let blackoutDates = {[
    "2022-03-01",
    "2022-03-08"
    "2022-04-13",
    "2022-05-22"
 ]}
}
<DatePicker
  disablePast
  value={checkout.rideDate}
  shouldDisableDate={getDisabledDates}
  onChange={(newValue) => {
   dispatch(setRideDate(newValue?.toISOString().split('T')[0]))
   }}
  renderInput={(params) => <TextField  className={classes.datePickerStyle} {...params}/>}
/>

Solution

  • shouldDisableDate is a function with the current date in param. So you need to compare this with your array, to enable / disable the date

    const shouldDisableDate= date => {
      let blackoutDates = {[
        "2022-03-01",
        "2022-03-08"
        "2022-04-13",
        "2022-05-22"
      ]}
    
      return blackoutDates.includes(date);
    }
    

    This is an exemple, as your date is of type Date whereas your array contains strings. So you'll need to convert the date to a YYYY-MM-DD string first, using your prefered way :)