How do I access the index of a selected item in list using React and Material UI?

Viewed 1428

I need to pass the index of the menu item selected onChange but don't know how to access it.

     const handleListChange = (e) => {
       console.log('Item Index: ', e.target.key);
     }


      <TextField
        select
        label="Select item"
        value={show}
        onFocus={getListArray}
        onChange={e => handleListChange(e)}
      >
        {listArray.map((value, index) =>
          <MenuItem
            key={index}
            value={value.title}
          >
            {value.title}
          </MenuItem>
        )}
      </TextField>
1 Answers

You can use map in order to get an array of titles and indexOf to get the index of the selected item.

And here it is with ES6 and arrow syntax, which is even simpler:

const handleListChange = (e) => {
  const index = listArray.map(item => item.title).indexOf(e.target.value);
  console.log(index);
}
Related