I am trying to call a function that handles onchange on autocomplete mui element, the event for the I tried e: React.ChangeEvent but I cannot find the element for the autocomplete component it gives the following error
Type '(e: React.ChangeEvent) => void' is not assignable to type '(event: ChangeEvent<{}>, value: string | null, reason: AutocompleteChangeReason, details?: AutocompleteChangeDetails | undefined) => void'.
any idea how to handle this element ?
// Function
const handleChange = (e: React.ChangeEvent<HTMLSelectElement>): void => {
//some logic
};
const handleTextField = (e: React.ChangeEvent<HTMLInputElement>): void => {
setText(e.target.value);
};
// Element
<Autocomplete
id='combo-box-demo'
key={bool}
options={options}
getOptionLabel={(option) => option}
onChange={handleChange}
className={classes.root}
renderInput={(params) => (
<TextField
onChange={handleTextField}
{...params}
InputLabelProps={{ shrink: false }}
label={!text.length && !e ? props.e ' e' : ' '}
/>
)}
/>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
To get the value from the onChange
event, you should use the second parameter as shown here
Also, the event type must be React.ChangeEvent
.
Here is a demo I created for you
Your onChange
function should be like this:
const handleChange = (e: React.ChangeEvent, value: string | null): void => {
console.log({ e, value });
};
Update:
As you said in the comments, you are trying to use the same onChange
handler for the native select
and autocomplete
components.
You should separate that two logic.
const handleNativeSelectChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
setSelected({ ...selected, [`${e.target.name}`]: e.target.value });
}
const handleMuiChange = (e: React.ChangeEvent, value: string | null) => {
setSelected({ ...selected, item: value });
}
const handleChange = (e: React.ChangeEvent, value: string | null): void => {
if (!!e.target.closest("button")) {
setSelected({ ...selected, item: "" });
setText("");
return;
}
if (e.target.id.startsWith("combo")) {
handleMuiChange(e, value)
} else {
handleNativeSelectChange(e as React.ChangeEvent<HTMLSelectElement>)
}
};