Unable to disable keyboard date change in MUI DatePicker API

Viewed 727

Link to CodeSandBox : codesandbox.io/s/dl5jft?file=/demo.tsx

I don't want users to Edit dates via keyboard, I want them to select dates from date picker modal, how to disable this?enter image description here,

i used the ReadOnly prop but it is disabling date selection itself, please help when i did readOnly, it is disabling the whole input, which made me unable to open the modal to select the date

    <GlobalStyle />
      <CalendarContainer>
        <LocalizationProvider dateAdapter={AdapterDateFns}>
          <DatePicker
            value={calendarVal}
            onChange={(newValue) => {
              handleChange(newValue);
            }}
            disabled={disabled}
            inputFormat="dd-MM-yyyy"
            renderInput={(params) => (
              <TextField
                // eslint-disable-next-line react/jsx-props-no-spreading
                {...params}
                name={name}
                error={error}
                disabled={disabled}
              />
            )}
          />
        </LocalizationProvider>
      </CalendarContainer>
2 Answers

For preventing user keyboard actions, you can set the functionality of onKeyDown event to preventDefault and assign it to TextField:

 const onKeyDown = (e) => {
    e.preventDefault();
 };

return (
<LocalizationProvider dateAdapter={AdapterDateFns}>
  <Stack spacing={3}>
    <DesktopDatePicker
      label="Date desktop"
      inputFormat="MM/dd/yyyy"
      value={value}
      onChange={handleChange}
      renderInput={(params) => (
        <TextField onKeyDown={onKeyDown} {...params} />
      )}
    />
)

Edit MaterialUIPickers Material Demo (forked)

I have done 2 things to solve this:

1- set render input TextField to readOnly => no typing

2- add sx of TextField caretColor: 'transparent' => hide the caret



<DatePicker
  renderInput={params => (
          <TextField
            {...params}
            InputProps={{
              readOnly: true,
            sx={{
              "& .MuiInputBase-input": {
                caretColor: 'transparent'
              }
            }}
          />
        )}
/>

Related