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?
- Click op the datepicker (not the icon)
- Click on another textfield
- Watch how the target/focus is back on the datepicker
CodePudding user response:
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