3

I want to disable dates before today or past dates. Below is how I approached it but it's not working. I can still choose the dates before today..

Date component:

type Props = {
  onDateChange: Function,
};

type State = {
  calendarOpen: boolean,
  month: moment,
  day: ?moment,
};

export default class AppearDateCalendar extends Component<Props, State> {
  state = {
    calendarOpen: false,
    month: moment(),
    day: undefined,
  };

  componentDidMount() {
    document.addEventListener('mousedown', this.handleClickOutside);
  }

  componentWillUnmount() {
    document.removeEventListener('mousedown', this.handleClickOutside);
  }

  handleClickOutside = (event: SyntheticMouseEvent<EventTarget>) => {
    const currentNode = ReactDOM.findDOMNode(this);
    if (currentNode && !currentNode.contains(event.target)) {
      this.setState({ calendarOpen: false });
    }
  };

  handleCalendarClick = () => {
    this.setState({ calendarOpen: !this.state.calendarOpen });
  };

  handleMonthChange = (_event: any, newMonth: moment) => {
    this.setState({ month: newMonth });
  };

  handleDaySelect = (_event, day: moment) => {
    this.props.onDateChange(day);
    this.setState({ day, calendarOpen: false });
  };

  dateDisplayText = (): string => {
    if (this.state.day) return this.state.day.format('Do MMM, YY');
    return t('choose_date');
  };

  render() {
    const today = new Date();

    return (
      <div className={cx(css.appearDateCalendar, this.state.calendarOpen ? css.focused : '')}>
        <div onClick={this.handleCalendarClick}>
          <h5 className={css.heading}>{t('heading')}</h5>
          <p className={css.dateText}>{this.dateDisplayText()}</p>
        </div>
        {this.state.calendarOpen && (
          <div className={css.calendarDropdown}>
            <DayPicker
              disabledDays={{ before: today }}
              month={this.state.month}
              onInteraction={this.handleDaySelect}
              onMonthChange={this.handleMonthChange}
            />
          </div>
        )}
      </div>
    );
  }
}

So I'm using disabledDays prop and setting before:today. Is that the way to do it or is there a better/right way to approach this? Any help/suggestions are welcome!

RH1922
  • 45
  • 1
  • 8

2 Answers2

4

This is the prop I added. It works for me:

dayPickerProps={{
        disabledDays: {
            before: new Date()
        }
    }}

Hope it helps !

ZeFifi
  • 157
  • 1
  • 13
0

Try using disabledDays with a date prop

<DayPicker
    disabledDays={{ before: new Date() }}
    month={this.state.month}
    onInteraction={this.handleDaySelect}
    onMonthChange={this.handleMonthChange}
/>
Jaich
  • 134
  • 1
  • 11