I'm working with multiple Autoplete MUI ponents and currently trying to write a "generic" event handler that will call useReducer
hook to store the state.
The problem is that in Autoplete
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 Autoplete 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 ponent that was changed?
I'm working with multiple Autoplete MUI ponents and currently trying to write a "generic" event handler that will call useReducer
hook to store the state.
The problem is that in Autoplete
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 Autoplete 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 ponent that was changed?
Share Improve this question asked Jun 26, 2020 at 4:29 KarenKaren 1,4295 gold badges27 silver badges50 bronze badges 1-
1
You could do
onChange={callback.bind(null, <your-identifier-here>}
. – hotpink Commented Jun 26, 2020 at 4:55
1 Answer
Reset to default 4The reason you get undefined is that the event.target
in the onChange
points to the li
but the MaterialUi Autoplete 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 (
<Autoplete
id="bo-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"
/>
)}
/>
);
}