How to show custom text (placeholder) in KeyboardDatePicker

Viewed 2411

I want to show "-select date-" placeHolder in datepicker if no date defined. Is that possible?

<MuiPickersUtilsProvider utils={DateFnsUtils}>
    <KeyboardDatePicker
        disableToolbar
        variant="inline"
        format="MM/dd/yyyy"
        margin="normal"
        id="date-picker-inline"
        disablePast
    />
</MuiPickersUtilsProvider>
3 Answers

You can provide a placeholder in the form of the placeholder prop.

<MuiPickersUtilsProvider utils={DateFnsUtils}>
    <KeyboardDatePicker
        placeholder='-select date-'
        disableToolbar
        variant="inline"
        format="MM/dd/yyyy"
        margin="normal"
        id="date-picker-inline"
        disablePast
    />
</MuiPickersUtilsProvider>

Check out the example on the official documentation page for more info.

OK. the solution is to add labelFunc prop

<MuiPickersUtilsProvider utils={DateFnsUtils}>
    <KeyboardDatePicker
        disableToolbar
        variant="inline"
        format="MM/dd/yyyy"
        margin="normal"
        id="date-picker-inline"
        labelFunc={() => selectedDate || '- Select date -'}
        disablePast
    />
</MuiPickersUtilsProvider>

or even better (assuming default date value == null):

<MuiPickersUtilsProvider utils={DateFnsUtils}>
    <KeyboardDatePicker
        disableToolbar
        variant="inline"
        format="MM/dd/yyyy"
        margin="normal"
        id="date-picker-inline"
        emptyLabel="- Select Date -"
        disablePast
    />
</MuiPickersUtilsProvider>

Yes, you can. don't get overwhelmed with null value and stuffs, this is one of many appropriate option you can do.

Try this out:

//You need all of these imports (a must)
import DateFnsUtils from '@date-io/date-fns';
import Moment from 'moment';
import { MuiPickersUtilsProvider, KeyboardDatePicker  } from "@material-ui/pickers";

//you need this too (a must)
const [selectDate, handleChangeSelectDate] = useState(null);

//Finally this is final thing you need
<MuiPickersUtilsProvider utils={DateFnsUtils}>
   <KeyboardDatePicker
      id="date-picker-inline"
      autoOk
      placeholder='-select date-'
      inputStyle={{ textAlign: 'center' }}
      variant="inline"
      inputVariant="outlined"
      format="MMM/dd/yyyy" //Can use MM if you want to show only number of month
      value={selectDate? moment(selectDate) : null}
      InputAdornmentProps={{ position: "start" }} //just use to put calendar icon on start or left position - remove it if you want it on end of the box or right hand side
      onChange={date => handleChangeSelectDate(date)}
   />
</MuiPickersUtilsProvider>
Related