Search code examples
reactjsreact-day-picker

how to enable two day only in react-day-picker


I need to enable two days only in my react-day-picker. The remaining days should be disabled. Could anyone give me an example of how to accomplish this?

I tried with this example but it not working for me.

export default function Example() {
  getDaysInMonth(month, year){
    // Since no month has fewer than 28 days
    let date = new Date(year, month, 1);
    const days = [];
    while (date.getMonth() === month) {
      dateys.push(new Date(date));
      date.setDate(date.getDate() + 1);
    }
    return days;
  }
  const disabledMonth = this.getDaysInMonth(12, 2017);
    return (
      <DayPicker
        initialMonth={new Date(2017, 3)}
        disabledDays={
          this.disabledMonth.filter(
            (date) => ![new Date(2017, 12, 3), new Date(2017, 12, 13)].includes(date)
          )
        }
      />
    );
}

i tried to run this code i getting empty array


Solution

  • An option is that you could set that the user should not be able to change the month if the two days are within the same month. You can set which month this is with initial month.

    You can then set the disabled days which will be an array of dates which is the days of that month excluding the two available days.

    Example:

    If you use something like this to have a method to get all dates in a month, you could do something like this:

    import React from 'react';
    import DayPicker from 'react-day-picker';
    import 'react-day-picker/lib/style.css';
    
    export default function Example() {
      const disabledMonth = getDaysInMonth(11, 2017);
    
      return (
        <DayPicker
          initialMonth={new Date(2017, 11)}
          disabledDays={
            this.disabledMonth.filter(
              (date) => ![new Date(2017, 11, 3).toString(), new Date(2017, 11, 13).toString()].includes(date.toString())
            )
          }
        />
      );
    }
    

    Here i am filtering out two dates, the 3rd and 13th of december, which should be available.

    This is written with es6