3

I have a Datepicker of Material that opens if you click on the textfield it belongs to. If you try to select another textfield while the datepicker is opened it will target/focus back to the datepicker.

Note: This issue is also for targeting nothing, it will refocus the datepicker again after closing it.

Example Demo: https://stackblitz.com/edit/react-b4xpki?file=demo.tsx

Code:

`

export default function BasicDatePicker() {
  const [value, setValue] = React.useState<Dayjs | null>(null);
  const [open, setOpen] = React.useState(false);

  return (
    <LocalizationProvider dateAdapter={AdapterDayjs}>
      <TextField placeholder='Click here while datepicker is opened' fullWidth={true} sx={{mb:2, mr: 2}}/>
      <DatePicker
        label="Basic example"
        value={value}
        onChange={(newValue) => {
          setValue(newValue);
        }}
        open={open}
        onOpen={() => setOpen(true)}
        onClose={() => setOpen(false)}
        renderInput={(props) => (
          <TextField {...props} onClick={(e) => setOpen(true)} />
        )}
      />
    </LocalizationProvider>
  );
}

So how to reproduce to problem?

  1. Click op the datepicker (not the icon)
  2. Click on another textfield
  3. Watch how the target/focus is back on the datepicker
  • Does this answer your question? [MUI - Open datepicker when clicking anywhere in the TextField](https://stackoverflow.com/questions/67053310/mui-open-datepicker-when-clicking-anywhere-in-the-textfield) – 0stone0 Nov 22 '22 at 13:50
  • Or this https://stackoverflow.com/questions/54060096/close-persistent-mui-drawer-on-clicking-outside – 0stone0 Nov 22 '22 at 13:59

1 Answers1

2

You can create focus named state so can control in onFocus at <TextField />

firstly, create focus named state:

const [focus, setFocus] = useState(false);

TextField: if open is false in onFocus, currentTarget shouldn't be focus.

 <TextField
     {...props}
      onFocus={(e) => {
          setFocus(open);
          if (!open) {
             e.currentTarget.blur();
             return;
          }
      }}
      focused={focus}
      onClick={(e) => setOpen((prev) => !prev)}
 />

if the value changes in DatePicker, focus should be true.

<DatePicker
    label="Basic example"
    value={value}
    onChange={(newValue) => {
      setValue(newValue);
       setFocus(true);
    }}
    ...otherProps
/>

link: https://stackblitz.com/edit/react-b4xpki-rirdxn?file=demo.tsx

Okan Karadag
  • 2,542
  • 1
  • 11
  • 23
  • Thanks, it is kinda strange that the datepicker won't open if clicking on the icon while the datepicker has an onOpen method.. / Edit: solved it by chaning the onclick just on setOpen(true) – user20521019 Nov 23 '22 at 08:06