LocalizationProvider localization crashes with an error - reactjs

I use
"material-react-table": "^1.6.5" | "#material-ui/core": "^4.12.4" | "#mui/material": "^5.11.7" | "#mui/styles": "^5.11.7" | "#mui/x-date-pickers" : "^5.0.18" | "#material-ui/pickers" : "3.0.0"
I'm taking an example
https://material-ui-docs.netlify.app/x/react-date-pickers/localization/
but
Filter: ({ column }) => (
<LocalizationProvider
adapterLocale="ru"
localeText={ruRU.components.MuiLocalizationProvider.defaultProps.localeText}
dateAdapter={AdapterDayjs}
>
<DatePicker
onChange={(newValue) => {
column.setFilterValue(newValue);
}}
renderInput={(params) => (
<TextField
{...params}
helperText={"Filter Mode: Lesss Than"}
sx={{ minWidth: "120px" }}
variant="standard"
/>
)}
value={column.getFilterValue()}
/>
</LocalizationProvider>
);
localization crashes with an error
Uncaught TypeError: Cannot read properties of undefined (reading 'L')
at index.js:36:1
at String.replace (<anonymous>)
at AdapterDayjs.expandFormat (index.js:34:1)
at AdapterDayjs.getFormatHelperText (index.js:41:1)
at useMaskedInput (useMaskedInput.js:23:1)
at KeyboardDateInput (KeyboardDateInput.js:29:1)
at renderWithHooks (react-dom.development.js:16305:1)
at updateForwardRef (react-dom.development.js:19226:1)
at beginWork (react-dom.development.js:21636:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
changed the version of dependencies, used CalendarPicker, "date-fns/locale/ru"

Related

Content editable throws, cannot read properties of undefined (reading 'textContent') in react app

I am trying to get text content typed from a content editable field in my react app, but getting below error;
Uncaught TypeError: Cannot read properties of undefined (reading 'textContent')
at handleChangeCode (admin.js:53:1)
at onInput (admin.js:157:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
at invokeGuardedCallback (react-dom.development.js:4277:1)
at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:4291:1)
at executeDispatch (react-dom.development.js:9041:1)
at processDispatchQueueItemsInOrder (react-dom.development.js:9073:1)
at processDispatchQueue (react-dom.development.js:9086:1)
const [createCode, setCreateCode] = useState([{ value: null }]);
function handleChangeCode(i, event) {
const codeValues = [...createCode];
codeValues[i].value = event.currentTarget.textContent;
setCreateCode(codeValues);
console.log(codeValues);
}
<div className='row'>
{createCode.map((code, idx) => {
return (
<div key={`${code}-${idx}`} className="dCodeArea">
<button type="button" onClick={() => handleRemoveCode(idx)}
className="closeElement">
X
</button>
<blockquote
type="text"
id="blogCode"
contenteditable='true'
className="codehighlight"
placeholder="Enter your code here"
value={code.value || ""}
onInput={e => handleChangeCode(idx, e.currentTarget.textContent)}
/>
</div>
);
})}
</div>
You're expecting event as the second parameter of handleChangeCode but you're calling it with event.currentTarget.textContent.
The string passed doesn't have .currentTarget (=> undefined), and undefined can't be queried for properties.
In short, use:
<blockquote onInput={e => handleChangeCode(idx, e) />

Material Autocomplete select dropdown getting error while onchange

Here is my code.
My problem : Cannot change the dropdown value. Getting error like Uncaught TypeError: Cannot read properties of undefined (reading 'id')
{formValues.map((element, index) => (
<div className="row mt-2" key={index}>
<div className='col-lg-4 mt-2' key={index}>
<Autocomplete
multiple
name="assignee"
limitTags={2}
id="assignee"
options={ownerList}
defaultValue={[{'text': formValues[index].AssigneeName, 'id': formValues[index].AssigneeId }]}
getOptionLabel={(option) => option.text}
onChange={(event, newValue) => {
console.log(newValue[0].id); // this line am getting error like Uncaught TypeError: Cannot read properties of undefined (reading 'id')
}}
disableClearable={true}
filterSelectedOptions
renderInput={(params) => (
<TextField
classes={{ root: classes.customTextField }}
{...params}
label="Select Assignee"
placeholder="Select Assignee"
className="auto-label"
/>
)}
/>
</div>
</div>
))}
Can you perhaps log console.log(newValue)? That would give you an insight on why you receive this error. Probably newValue[0] is undefined.
You can add optional chaining to prevent the Error. console.log(newValue[0]?.id);

Disable manual input for MUI TimePicker

I have a bit of a custom TimePicker provided from Material UI. I add an ability for the user to select only whole hours, such as 15:00, 16:00 etc. by clicking on a clock icon
What I want to achieve is to add same for manual input of the text field. For now user can manually add any valid time, for example 14:34, which is incorrect for my case
Can anyone help me?
Here is my TimePicker:
<LocalizationProvider dateAdapter={AdapterDateFns} locale={locale}>
<TimePicker
ampm={false}
openTo="hours"
views={['hours']}
inputFormat="HH:mm"
mask="__:__"
value={dayStartValue}
InputAdornmentProps={{
position: 'start',
}}
components={{
OpenPickerIcon: ClockFilledIcon,
}}
onChange={(newValue) => {
setDayStartValue(newValue)
}}
renderInput={(params) =>
<TextField
{...params}
helperText="Input start of Day time"
/>
}
/>
</LocalizationProvider>
You can control and validate the user's input when he clicks away from the time picker by using onBlur inside InputProps.
import * as React from "react";
import TextField from "#mui/material/TextField";
import { AdapterDateFns } from "#mui/x-date-pickers/AdapterDateFns";
import { LocalizationProvider } from "#mui/x-date-pickers/LocalizationProvider";
import { TimePicker } from "#mui/x-date-pickers/TimePicker";
export default function BasicTimePicker() {
const [dayStartValue, setDayStartValue] = React.useState<Date | null>(null);
return (
<LocalizationProvider
dateAdapter={AdapterDateFns}
locale={locale}
>
<TimePicker
ampm={false}
openTo="hours"
views={["hours"]}
inputFormat="HH:mm"
mask="__:__"
value={dayStartValue}
InputAdornmentProps={{
position: "start"
}}
components={{
OpenPickerIcon: ClockFilledIcon,
}}
onChange={(newValue: Date, keyboardInputValue?: string) => {
setDayStartValue(newValue);
}}
renderInput={(params) => (
<TextField {...params} helperText="Input start of Day time" />
)}
InputProps={{
onBlur: (
e: React.FocusEvent<HTMLInputElement | HTMLTextAreaElement, Element>
) => {
const newDate = new Date(dayStartValue);
newDate.setMinutes(0);
if (e.target.value && e.target.value.length === 5) {
setDayStartValue(newDate);
}
}
}}
/>
</LocalizationProvider>
);
}
For the validation we check the user input and if it's a valid Date (5 characters length), we create a new Date with that and set the minutes to 0.
Code Sandbox example
You can change your input format and the mask to only accept whole hours like so:
<LocalizationProvider dateAdapter={AdapterDayjs}>
<TimePicker
ampm={false}
openTo="hours"
views={['hours']}
inputFormat="HH:00"
mask="__:00"
value={value}
InputAdornmentProps={{
position: 'start',
}}
onChange={(newValue) => {
setValue(newValue)
}}
renderInput={(params) =>
<TextField
{...params}
helperText="Input start of Day time"
/>
}
/>
</LocalizationProvider>
sandbox

material ui - Autocomplete multiple error

I am using material-ui in React.js. When using multiple in Autocomplete it gives me the error,
Uncaught TypeError: (intermediate value)(intermediate value)(intermediate value).filter is not a function at useAutocomplete,
The above error occurred in the <ForwardRef(Autocomplete)> component:
in ForwardRef(Autocomplete).
material-ui version - "#mui/material": "^5.6.0",
Code:
<Autocomplete
multiple={true}
disableCloseOnSelect
id={field.name}
name={field.name}
options={locations}
value={props.values.locationId}
size="small"
autoComplete={false}
onChange={(e, newValue) => {
props.setFieldValue(
'locationId',
newValue ? newValue : '',
true,
);
}}
onBlur={() =>
props.setFieldTouched(field.name, true)
}
getOptionLabel={(option) =>
option['name'] ? option['name'] : ''
}
renderOption={(props, option, { selected }) => (
<li {...props}>
<Checkbox
style={{ marginRight: 8 }}
checked={selected}
/>
{option.title}
</li>
)}
renderInput={(params) => (
<TextField
{...params}
fullWidth
size="small"
placeholder={field.placeholder}
variant="outlined"
/>
)}
/>
When using multiple, value must be an array (see multiple in the docs). I found this answer helpful for using a controlled Autocomplete component in multiple mode, as you're doing here.

TextField in MenuItem causes nextFocus.getAttribute is not a function

I have created a Menu with Material UI that pops up when a button gets clicked. This Menu displays a dynamic list of id's that can get filtered with a Textfield positioned at the top of the Menu. But when I'm typing inside of the textfield I get the error: Uncaught TypeError: nextFocus.getAttribute is not a function.
I have no Idea what could cause this issue and how it can be resolved.
This is the code of my SearchableFilter component that is shown on the image above. I have removed some unnecessry styling in the code
const SearchableFilter = ({ values, label, setState, state }) => {
const classes = useStyles();
const [focused, setFocused] = React.useState(false);
const [anchorEl, setAnchorEl] = React.useState(null);
const [searchValue, setSearchValue] = useState("");
const openMenu = (event) => {
setFocused(true);
setAnchorEl(event.currentTarget);
};
const selectItem = (value) => {
handleClose();
setState(value);
};
const handleDelete = () => {
setState("");
};
const handleChange = (event) => {
return setSearchValue(event.target.value);
};
const filteredValues = values.filter((value) =>
value.includes(searchValue.trim())
);
const handleClose = () => {
setFocused(false);
setAnchorEl(null);
};
return (
<div className={classes.margin}>
<Button
aria-controls="simple-menu"
aria-haspopup="true"
onClick={openMenu}
disableRipple
endIcon={<ArrowDropDownIcon color={state && "primary"} />}
>
{label}
</Button>
<Menu
id="menu-appbar"
anchorEl={anchorEl}
getContentAnchorEl={null}
anchorOrigin={{ vertical: "bottom", horizontal: "left" }}
open={Boolean(anchorEl)}
elevation={2}
onClose={handleClose}
>
<MenuItem
button={false}
dense={true}
key="input"
className={classes.menuItem}
>
<TextField
id="input"
label="Search"
value={searchValue}
onChange={handleChange}
/>
</MenuItem>
<List style={{ maxHeight: "300px", overflow: "auto" }}>
{filteredValues.map((value) => (
<MenuItem
key={value}
dense={true}
className={classes.menuItem}
disableGutters={true}
onClick={() => selectItem(value)}
>
{value}
</MenuItem>
))}
</List>
</Menu>
</div>
);
};
Full error:
Uncaught TypeError: nextFocus.getAttribute is not a function
at moveFocus (MenuList.js:76)
at handleKeyDown (MenuList.js:188)
at HTMLUnknownElement.callCallback (react-dom.development.js:3945)
at Object.invokeGuardedCallbackDev (react-dom.development.js:3994)
at invokeGuardedCallback (react-dom.development.js:4056)
at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:4070)
at executeDispatch (react-dom.development.js:8243)
at processDispatchQueueItemsInOrder (react-dom.development.js:8275)
at processDispatchQueue (react-dom.development.js:8288)
at dispatchEventsForPlugins (react-dom.development.js:8299)
at react-dom.development.js:8508
at batchedEventUpdates$1 (react-dom.development.js:22396)
at batchedEventUpdates (react-dom.development.js:3745)
at dispatchEventForPluginEventSystem (react-dom.development.js:8507)
at attemptToDispatchEvent (react-dom.development.js:6005)
at dispatchEvent (react-dom.development.js:5924)
at unstable_runWithPriority (scheduler.development.js:468)
at runWithPriority$1 (react-dom.development.js:11276)
at discreteUpdates$1 (react-dom.development.js:22413)
at discreteUpdates (react-dom.development.js:3756)
at dispatchDiscreteEvent (react-dom.development.js:5889)
Edit:
Here is a CodeSandBox that displays the error:
Answer provided by #Ryan Cogswell in the comments.
Adding the onKeyDown prop to the parent MenuItem of the TextField fixed my issue.
<MenuItem
button={false}
onKeyDown={e => e.stopPropagation()}
>
<TextField
onChange={handleChange}
value={value}
/>
</MenuItem>
As answere by JonasLevin.
If you have any div or other element wrapping Textfield , you should add
onKeyDown={e => e.stopPropagation()}
to that element

Resources