readOnly MobileDatePicker doesn't work in MUI v5

Viewed 444

The readOnly flag for MUI MobileDatePicker doesn't work. The API has no effect on onClick functionality. The only workaround is to use disabled flag. However, we use both readOnly and disabled functionalities for different uses cases. Any help appreciated.

<MobileDatePicker
  label="Date mobile"
  disableOpenPicker
  inputFormat="MM/dd/yyyy"
  value={value}
  readOnly
  onChange={handleChange}
  renderInput={(params) => (
    <TextField {...params} InputProps={{ readOnly: true }} />
  )}
/>
1 Answers

Looks like the TextField inside is read-only but the picker is not and you can open the picker by clicking the TextField. An easy workaround is to always set the open state to false to prevent the picker from being opened:

<MobileDatePicker readOnly open={false}

If you need to change the readonly value dynamically:

function EnhancedMobileDatePicker(props) {
  const [open, setOpen] = React.useState(false);
  const { readOnly } = props;

  React.useEffect(() => {
    // do not auto open picker after setting readOnly to false
    if (!readOnly) setOpen(false);
  }, [readOnly]);

  return (
    <MobileDatePicker
      {...props}
      readOnly={readOnly}
      open={readOnly ? false : open}
      onOpen={() => setOpen(true)}
      onClose={() => setOpen(false)}
    />
  );
}

Codesandbox Demo

Related