coder1234321
coder1234321

Reputation: 51

MUI v5 - Can't access MenuItem attribute through event.currentTarget after update

I previously was on v4 and had my Select and MenuItems setup like so:

const [select, setSelect] = useState('');
const [customName, setCustomName] = useState('');

const handleChange = (event) => {
    setSelect(event.target.value);
    setCustomName(event.currentTarget.getAttribute('name'));
  };

...

                <Select
                  label="Choose A Dataset"
                  onChange={handleChange}
                  value={select}
                >
                  {tables &&
                    tables.map(
                      (table, index) =>
                          (
                          <MenuItem
                            key={table.name}
                            value={table.code}
                            name={table.name}
                          >
                            {table.name}
                          </MenuItem>
                        )
                    )}
                </Select>

and I could access the menuItem's name attribute through

event.currentTarget.getAttribute('name');

However, after the migration to v5, event.currentTarget returns null. Any suggestions?

Upvotes: 4

Views: 1101

Answers (1)

The SelectInput has this onChange definition:

onChange?: (event: SelectChangeEvent<T>, child: React.ReactNode) => void;

meaning that you can get the child clicked as the second param on your handleChange. Here you can access the name property with child.props.name.

However it's worth noting that MenuItem doesn't have a name prop and if you define it Typescript will highlight it as an error. To avoid this you could use the event.target.value to find the table with the matching code and get the name that way:

const name = tables.find((table) => table.code === event.target.value).name;

Upvotes: 3

Related Questions