MUI - Open datepicker when clicking anywhere in the TextField

Viewed 6968

I have a date picker that I want to show when the users click anywhere in the field not just on the calendar icon.

Here's the picker

enter image description here

export function DatePickerField(props) {
  ......

  return (
      <Grid container>
          <MuiPickersUtilsProvider utils={DateFnsUtils}>
              <KeyboardDatePicker
                  {...field}
                  {...props}
                  disableToolbar
                  inputVariant="outlined"
                  value={selectedDate}
                  onChange={_onChange}
                  error={isError}
                  autoOk
                  invalidDateMessage={isError && error}
                  helperText={isError && error}
              />
          </MuiPickersUtilsProvider>
      </Grid>
  );
}

I need to do this because if date entered manually, it throws no errors but I get invalid date in the form data.

How can show the picker when the field is clicked?

1 Answers

MUI v5 added the DatePicker component in the @mui/lab package. If you want a picker to be opened after when the user clicked inside the TextField, use MobileDatePicker, this doesn't have the calendar icon though, see this answer if you want to have one.

<MobileDatePicker
  {...}
  renderInput={(params) => <TextField {...params} />}
/>

The DesktopDatePicker however does have the calendar icon, but you have to write additional code to control the open state and tell the picker to open when TextField is clicked:

<DatePicker
  open={open}
  onOpen={() => setOpen(true)}
  onClose={() => setOpen(false)}
  renderInput={(params) => {
    return (
      <TextField
        {...params}
        onClick={(e) => setOpen(true)}
      />
    );
  }}
/>

Codesandbox Demo


Original Answer

You can control the KeyboardDatePicker's open state and set it to true when the TextField is clicked:

const [open, setOpen] = useState(false);

return (
  <KeyboardDatePicker
    open={open}
    onOpen={() => setOpen(true)}
    onClose={() => setOpen(false)}
    TextFieldComponent={(props) => (
      <TextField {...props} onClick={(e) => setOpen(true)} />
    )}
    {...other}
  />
);

Live Demo

Edit 67053310/material-ui-datepicker

Related