react-native-calendars icon indicating copy to clipboard operation
react-native-calendars copied to clipboard

Disable a row of days (e.g. disable all Sundays)

Open yayanartha opened this issue 9 years ago • 18 comments

How to disable a row of days, like all Sundays or all Saturdays?

yayanartha avatar Jun 01 '17 02:06 yayanartha

Hi, you can specify which dates are disabled in markedDates prop

tautvilas avatar Jun 21 '17 04:06 tautvilas

@tautvilas I may be missing something on this comment. I see you can explicitly disable a date (eg. 10/06/2017), but a given set of days in a week (eg. disable all weekend days like Saturday or Sunday) is infinite. How is that done with this plugin?

arinhouck avatar Oct 07 '17 00:10 arinhouck

@tautvilas Seconding @arinhouck , how would one disable Weekends without a bunch of extra processing?

jeffmwells avatar Nov 01 '17 12:11 jeffmwells

Curious about this as well.

404sand808s avatar Jan 08 '18 15:01 404sand808s

Something new?! I need it. :*

rodrix avatar Jan 10 '18 18:01 rodrix

implementing a day component and setting state to disabled if it's a weekend is a workaround. example from @eddiegroves here: https://github.com/wix/react-native-calendars/issues/280

jebora avatar Jan 10 '18 19:01 jebora

Worked this up:

`let markedDates = {

  [moment().format('YYYY-MM-DD')]: {marked: true, dotColor: PINK_DARK}, // mark today with a red dot
  [this.state.selected]: {selected: true}
}

for (i = 1; i < 13; i++ ) { // figure out if the next X days are weekend days and if so disable them

  let day = moment().add(i, 'd')

  if (day.isoWeekday() === 6 || day.isoWeekday() === 7) {
    markedDates[day.format('YYYY-MM-DD')] = {disabled: true}
  }
}`

After that pass markedDates to the calendar component as a markedDates prop. I only needed it for the next week or two so I ran it few times. If you need a fix to disable weekends far into the future I’m not sure if this would be efficient.

404sand808s avatar Jan 10 '18 22:01 404sand808s

I should have followed up here earlier, I disabled based on month change. This worked out perfectly.

const DISABLED_DAYS = ['Saturday', 'Sunday']
state = {
    markedDates: this.getDaysInMonth(moment().month(), moment().year(),  DISABLED_DAYS)
  }
onMonthChange={(date) => {
              this.setState({
                markedDates: this.getDaysInMonth(date.month - 1, date.year, DISABLED_DAYS)
              })
            }}
  getDaysInMonth(month, year, days) {
    let pivot = moment().month(month).year(year).startOf('month')
    const end = moment().month(month).year(year).endOf('month')

    let dates = {}
    const disabled = { disabled: true }
    while(pivot.isBefore(end)) {
      days.forEach((day) => {
        dates[pivot.day(day).format("YYYY-MM-DD")] = disabled
      })
      pivot.add(7, 'days')
    }

    return dates
  }

arinhouck avatar Jan 18 '18 00:01 arinhouck

@arinhouck @404sand808s what is moment()?

NarendraSingh88 avatar Jun 05 '18 10:06 NarendraSingh88

@NarendraSingh88 it's a JS library for time/date manipulation. https://momentjs.com/

jebora avatar Jun 05 '18 13:06 jebora

For anyone reaching here ... And trying to use @arinhouck answer...

Juste know that const disabled = { disabled: true } isn't enough to disable the onDayPress trigger

replace it with : const disabled = { disabled: true, disableTouchEvent: true };

Also there's a mistake in the getDaysInMonth fucntion :

During the forEach trying to create the key for the dates object the variable pivot is modified so it skip some weeks ...

Here is my version (I've change the ['Saturday', 'Sunday'] with days indexes to get ride of the locales) :

const DatePicker = ({
  date,
  setDate,
  initDate = new Date(),
  minimumDate = new Date(),
  disabledDaysIndexes = [6, 7],
}) => {
  const [markedDates, setMarkedDates] = useState({});
  
  // And don't forget to disabled the "first" dates on init : 
  useEffect(() => {
    getDisabledDays(
      initDate.getMonth(),
      initDate.getFullYear(),
      disabledDaysIndexes
    );
  }, []);

  const getDisabledDays = (month, year, daysIndexes) => {
    let pivot = moment().month(month).year(year).startOf('month');
    const end = moment().month(month).year(year).endOf('month');
    let dates = {};
    const disabled = { disabled: true, disableTouchEvent: true };
    while (pivot.isBefore(end)) {
      daysIndexes.forEach((day) => {
        const copy = moment(pivot);
        dates[copy.day(day).format('YYYY-MM-DD')] = disabled;
      });
      pivot.add(7, 'days');
    }
    setMarkedDates(dates);
    return dates;
  };

  <Calendar
    theme={{
      textSectionTitleDisabledColor: '#d9e1e8',
    }}
    markedDates={markedDates}
    current={initDate}
    minDate={minimumDate}
    onDayPress={(day) => {
      setDate(day.dateString);
    }}
    firstDay={1}
    enableSwipeMonths={true}
    disabledDaysIndexes={disabledDaysIndexes}
    onMonthChange={(date) => {
      getDisabledDays(date.month - 1, date.year, disabledDaysIndexes);
    }}
  />;
};

seba9999 avatar Oct 12 '21 16:10 seba9999

simple solution

const checkDay = (value: string) => value.split(" ")[1] === 'Saturday' || value.split(" ")[1] === 'Sunday'

<Calendar
 dayComponent={({accessibilityLabel, date, state}: any) => {

       return (
         <View>
           <Text style={[styles.days, (checkDay(accessibilityLabel) || state)  && styles.disabled]}>
             {date.day}
           </Text>
         </View>
       );
     }}
 />

ArtemBozhenko avatar Dec 03 '21 12:12 ArtemBozhenko

onDayPress={(day) => { var date = new Date(day.dateString); if (date.getDay() != 6 && date.getDay() != 7) console.log("selected day", day); }} to disable just the press event, no ui marking

PetroviciMihail avatar Jun 19 '22 08:06 PetroviciMihail

image Hello guys, i have this issue. When first day of month is Sunday then will became like this.. That's weird. Other day is working fine, just when this happened.

And yaa i am using this formula as well.

const getDisabledDays = (month, year, daysIndexes) => {

let pivot = moment().month(month).year(year).startOf("month")
const end = moment().month(month).year(year).endOf("month")
let dates = {}

const disabled = { disabled: true, disableTouchEvent: true }
while (pivot.isBefore(end)) {
  daysIndexes.forEach((day) => {
    const copy = moment(pivot)
    dates[copy.day(day).format("YYYY-MM-DD")] = disabled
  })
  pivot.add(7, "days")
}
setDisableDates(dates)
return dates

}

NoahSimajji avatar Dec 31 '22 08:12 NoahSimajji

@NoahSimajji I had the same problem, I fixed this with this approach:

const getDisabledDays = (month, year, daysIndexes) => {

  let pivotDay = moment().month(month).year(year).startOf('month')
  const lastDayOfMonth = moment().month(month).year(year).endOf('month')
  
  let disabledDates = {}
  
  const disabledProps = { disabled: true, disableTouchEvent: true }
  
  let allDayOfMonthChecked = false

  while (!allDayOfMonthChecked) {
    if (!pivotDay.isBefore(lastDayOfMonth)) {
      allDayOfMonthChecked = true
    }
  
    daysIndexes.forEach(day => {
      const copy = moment(pivotDay)
      disabledDates[copy.day(day).format('YYYY-MM-DD')] = disabledProps
    })
    pivotDay.add(7, 'days')
  }
   setDisableDates(disabledDates)
   return disabledDates
}

Please @NoahSimajji , let me know if this works for you

Jean-Kenned avatar Jan 14 '23 00:01 Jean-Kenned

Hi, Another approach is this:

  const isSunday = (date: Date) => {
    const day = date.getDay();
    return day === 0;
  };

  const getDisabledSundays = (minDate: string, maxDate: string) => {
    const start = new Date(minDate);
    const end = new Date(maxDate);
    const disabledSundays: {
      [key: string]: {disabled: boolean; disableTouchEvent: boolean};
    } = {};

    const currentDate = start;
    while (currentDate <= end) {
      if (isSunday(currentDate)) {
        const dateString = currentDate.toISOString().split('T')[0];
        disabledSundays[dateString] = {disabled: true, disableTouchEvent: true};
      }
      currentDate.setDate(currentDate.getDate() + 1);
    }
    return disabledSundays;
  };

  const markedDates = useMemo(() => {
    const minDate = DateUtilities.formattedDayFromToday(1);
    const maxDate = DateUtilities.formattedDayFromToday(30);
    const disabledSundays = getDisabledSundays(minDate, maxDate);

    return {
      [selectedDate]: {
        selected: true,
        disableTouchEvent: true,
        selectedColor: theme.colors.primary,
        selectedTextColor: theme.colors.lightText,
      },
      ...disabledSundays,
    };
  }, [selectedDate]);

  return (
    <ReactNativeCalendar
      firstDay={1}
      markedDates={markedDates}
      maxDate={DateUtilities.formattedDayFromToday(30)}
      minDate={DateUtilities.formattedDayFromToday(1)}
      onDayPress={handleDayPress}
      theme={{
        selectedDayBackgroundColor: 'transparent',
        selectedDayTextColor: '#D9E1E8',
      }}
    />

thecoder93 avatar Jul 04 '24 10:07 thecoder93

Here is the working Code:

import React, { useEffect, useState, useCallback } from 'react';
import { ExpandableCalendar, CalendarProvider, WeekCalendar } from 'react-native-calendars';
import { useColors } from '../constants/Colors';
import { MarkedDates } from 'react-native-calendars/src/types';
import moment from 'moment';
import { CalendarProps } from "react-native-calendars/src/calendar";

interface Props {
    weekView?: boolean;
    showTodayButton?: boolean;
    blockedDate?: string[];
    blockedDays?: string[];
    handleDateChange?: (date: object) => void;
}

const CustomExpandableCalendar: React.FC<Props> = ({
    handleDateChange,
    weekView = false,
    showTodayButton = false,
    blockedDate = [],
    blockedDays = [],
}: Props) => {
    const colors = useColors();
    const [markedDates, setMarkedDates] = useState<MarkedDates>({});
    const [yearRange, setYearRange] = useState(1);

    const calculateBlockedDates = useCallback((): MarkedDates => {
        const newMarkedDates: MarkedDates = {};

        blockedDate?.forEach(date => {
            newMarkedDates[date] = { disabled: true, disableTouchEvent: true };
        });

        const startDate = moment();
        const endDate = moment().add(yearRange, 'years');
        const daysToDisable = blockedDays?.map(day =>
            ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"].indexOf(day)
        );

        for (let date = startDate.clone(); date.isBefore(endDate); date.add(1, 'day')) {
            if (daysToDisable.includes(date.day())) {
                newMarkedDates[date.format('YYYY-MM-DD')] = {
                    disabled: true,
                    disableTouchEvent: true,
                };
            }
        }

        return newMarkedDates;
    }, [blockedDate, blockedDays, yearRange]);

    useEffect(() => {
        setMarkedDates(calculateBlockedDates());
    }, [calculateBlockedDates]);

    const handleMonthChange = (date: any) => {
        const selectedDate = moment(date.dateString);
        const endOfCurrentRange = moment().add(yearRange, 'years').subtract(1, 'months');
        if (selectedDate.isAfter(endOfCurrentRange)) {
            setYearRange(prevRange => prevRange + 1);
        }
    };

    const getTheme = () => ({
        backgroundColor: colors.background,
        calendarBackground: colors.background,
        selectedDayBackgroundColor: colors.primaryColor,
        selectedDayTextColor: colors.text,
        todayTextColor: colors.primaryColor,
        dayTextColor: colors.text,
        textDisabledColor: colors.primaryGrey,
        monthTextColor: colors.primaryColor,
        textDayFontWeight: 'bold',
        textMonthFontWeight: '600',
        textDayHeaderFontWeight: '600',
        arrowColor: colors.primaryColor,
    }) as CalendarProps['theme'];

    return (
        <CalendarProvider
            date={moment().format('YYYY-MM-DD')}
            showTodayButton={showTodayButton}
            theme={{ todayButtonTextColor: colors.primaryColor }}
            collapsable
        >
            {weekView ? (
                <WeekCalendar
                    theme={getTheme()}
                    firstDay={1}
                    markedDates={markedDates}
                    onDayPress={handleDateChange}
                    onMonthChange={handleMonthChange}
                    markingType="custom"
                />
            ) : (
                <ExpandableCalendar
                    allowShadow
                    theme={getTheme()}
                    firstDay={1}
                    markedDates={markedDates}
                    onDayPress={handleDateChange}
                    onMonthChange={handleMonthChange}
                    animateScroll
                    markingType="custom"
                />
            )}
        </CalendarProvider>
    );
};

export default CustomExpandableCalendar;


anishniroula1 avatar Nov 06 '24 05:11 anishniroula1

I did it this way:

 export const getDisabledDatesInMonth = (
        month: number,
        year: number,
        disabledDays: number[]
    ) => {
        let pivot = dayjs().month(month).year(year).startOf("month");
        const end = dayjs().month(month).year(year).endOf("month");

        let dates: { [key: string]: MarkingProps } = {};
        const disabled: MarkingProps = {
            disabled: true,
            disableTouchEvent: true,
        };

        while (pivot.subtract(7, "days").isBefore(end)) {
            disabledDays.forEach((day) => {
                const copy = dayjs(pivot);
                dates[copy.day(toDayJsDay(day)).format("YYYY-MM-DD")] =
                    disabled;
            });

            pivot = pivot.add(7, "days");
        }
        return dates;
    };

This part was the most critical change

        while (pivot.subtract(7, "days").isBefore(end)) {

This is because if pivot reaches lets say March 1, 2025, It will no longer add the last week of February to the disabled object, so we want to keep the loop going until it no longer touches the month even after pivoting the days based on the disabledDays

toDayJsDay is just

    export const toDayJsDay = (day: number) => (day === 7 ? 0 : day);

MisterMunchkin avatar Nov 10 '24 07:11 MisterMunchkin