javascriptreactjsmaterial-uicalendar

Unable to disable keyboard date change in MUI DatePicker API


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>

Solution

  • For preventing user keyboard actions, you can set the functionality of the 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)