Peter
Peter

Reputation: 407

Deactivate current and past days in Material-UI Datepicker

I would like to deactivate the current day in the picker. The first day which should be able to be selected by the user is basically current day + 1. Today is the 15th, so they are only able to choose dates starting from the 16th.

import React from "react";
import * as PropTypes from "prop-types";
import {
    MuiPickersUtilsProvider,
    KeyboardDatePicker,
} from "@material-ui/pickers";
import DateFnsUtils from "@date-io/date-fns";
import enLocale from "date-fns/locale/en-US";
import deLocale from "date-fns/locale/de";

import { useUserLocale } from "../../customHooks/user";

const localeMap = {
    en: enLocale,
    de: deLocale,
};

function DatePicker(props) {
    const { name, selectedDate, setSelectedDate } = props;

    const locale = useUserLocale();

    const handleDateChange = date => {
        setSelectedDate(date);
    };

    return (
        <MuiPickersUtilsProvider
            utils={DateFnsUtils}
            locale={localeMap[locale]}
        >
            <KeyboardDatePicker
                disableToolbar
                variant="inline"
                format={locale === "de" ? "dd.MM.yyyy" : "MM/dd/yyyy"}
                id="date-picker-inline"
                label={name}
                value={selectedDate}
                onChange={handleDateChange}
                fullWidth
                KeyboardButtonProps={{
                    "aria-label": "change date",
                }}
                autoOk
                disablePast
            />
        </MuiPickersUtilsProvider>
    );
}

DatePicker.propTypes = {
    name: PropTypes.string.isRequired,
    selectedDate: PropTypes.instanceOf(Date).isRequired,
    setSelectedDate: PropTypes.func.isRequired,
};

export default DatePicker;

Upvotes: 0

Views: 2553

Answers (1)

Domino987
Domino987

Reputation: 8774

As mentioned in the docs, you can simply create a min Date with new Date(new Date().getTime() + 86400000) and you can set that with the minDate prop.

If you combine that to set the initial date to be after this min date, it will work.

const minDate = new Date(new Date().getTime() + 86400000);

function DatePicker(props) {
  const { name, selectedDate, setSelectedDate } = props;

  const locale = useUserLocale();

  const handleDateChange = date => {
    setSelectedDate(date);
  };

  return (
    <MuiPickersUtilsProvider utils={DateFnsUtils} locale={localeMap[locale]}>
      <KeyboardDatePicker
        disableToolbar
        variant="inline"
        format={locale === "de" ? "dd.MM.yyyy" : "MM/dd/yyyy"}
        id="date-picker-inline"
        label={name}
        minDate={minDate}
        value={selectedDate}
        onChange={handleDateChange}
        fullWidth
        KeyboardButtonProps={{
          "aria-label": "change date"
        }}
        autoOk
        disablePast
      />
    </MuiPickersUtilsProvider>
  );
}

Upvotes: 1

Related Questions