I'm working with multiple Autocomplete MUI components and currently trying to write a "generic" event handler that will call useReducer
hook to store the state.
The problem is that in Autocomplete
docs, onChange function looks like the following:
function(event: object, value: T | T[], reason: string) => void
I'm trying to get the name of a field from the event object (to determine what Autocomplete is being changed), but event.target.name
and event.currentTarget.name
are not working.
Are there are any ways to retrieve the name of a component that was changed?
The reason you get undefined is that the event.target
in the onChange
points to the li
but the MaterialUi Autocomplete will add the name
to the outer div
. So, there is no straight forward way. You can use a ref
and use getAttribute
to get the name.
Code snippet
export default function ComboBox() {
const ref0 = useRef();
return (
<Autocomplete
id="combo-box-demo"
ref={ref0}
name="movies"
options={top100Films}
getOptionLabel={option => option.title}
onInputChange={(e, v, r) => {
const ev = e.target;
if (r === "reset") console.log(ev, v, r);
}}
onChange={(e, v, r) => {
console.log(ref0.current.getAttribute("name"));
}}
style={{ width: 300 }}
renderInput={params => (
<TextField
name="auto-input"
{...params}
label="Combo box"
variant="outlined"
/>
)}
/>
);
}