drifterOcean19
drifterOcean19

Reputation: 392

momentjs and react - to disable days checked against an array of days

<Query query={GET_SPACE} 
  variables={{ 
    spaceId: this.props.spaceId,
    fromDate: today,
    toDate: moment().add(3, 'years').format('YYYY-MM-DD'),
  }}
>
  {({ loading, error, data }) => {
    if (loading) return null;
    if (error) return null;

    const { space } = data;
    const days = space.calendar.days;

    return (
      <div className={css.datePickerContainer}>
        <DayRangePicker
          month={month}
          selectDate={selectDate}
          startDate={startDate}
          endDate={endDate}
          onInteraction={this.handleDayPickerChange}
          onMonthChange={this.handleMonthChange}
          isDisabled={(d) => d.isBefore(today, 'day')}
          classNames={{header: 'fs-ignore-rage-clicks'}}
        />
      </div>
    );
  }}
</Query>

In this query, I have a constant days that gives me an array of bookable days and each day has date, bookable which can be true or false, and open which can also be true or false like below:

{
  "date": "2019-07-01",
  "bookable": true,
  "open": true
}

What I want to achieve now is something like below.. to disable days that has bookable : false.

isDisabled={(d) => d.isBefore(today, 'day') && disable days that has bookable: false}
where d is a moment.

What's the best way to do this?

Upvotes: 0

Views: 60

Answers (2)

user7143559
user7143559

Reputation:

If I understood correctly, something like this would work:

isDisabled={(d) => d.isBefore(today, 'day') && days.find(day => day.date === d.format('YYYY-MM-DD') && !day.bookable)

A bit of explanation:

days.find will return the first element of the array which returns true with the function provided. This element is truthy, therefore the condition is correct. If not found, days.find will return undefined, cancelling the condition.

Upvotes: 1

rebecca
rebecca

Reputation: 963

You could include an array with unbookable dates and check if the current date is inside it:

{({ loading, error, data }) => {
if (loading) return null;
if (error) return null;

const { space } = data;
const days = space.calendar.days;
//filter the nonbookable objects than return only date
const notBookable = days.filter((el) => !el.bookable).map((elem) => return elem.date);
return (
  <div className={css.datePickerContainer}>
    <DayRangePicker
      month={month}
      selectDate={selectDate}
      startDate={startDate}
      endDate={endDate}
      onInteraction={this.handleDayPickerChange}
      onMonthChange={this.handleMonthChange}
      isDisabled={(d) => d.isBefore(today, 'day') && notBookable.includes(d)}
      classNames={{header: 'fs-ignore-rage-clicks'}}
    />
  </div>
);
}}

and same as the other poster: would work as long as d is the same format as date.

to make it complete and if d is a different format use notBookable.includes(d.format('YYYY-MM-DD'))

Upvotes: 0

Related Questions