javaFE
javaFE

Reputation: 39

React.js MaterialUI: How to bind the value of a materiaUI select dropdown with the corrispective list item value?

I have a list of users and a Select dropdown from material UI with some values. I am able to console.log the values of the select but how can I know to which user in the List they refer to?

   <List>
    {userList.map((user:any) => (
      <ListItem  key={user.key}>
        <ListItemAvatar>
          <Avatar>
            <PersonIcon />
          </Avatar>
        </ListItemAvatar>
        <ListItemText primary={user.name} />
        <Select
                 
                 value={userValue}
                 
                 onChange={handleChange}
                 
               >
                 {dropdownvalues.map(
                   (g: { value: string}) => (
                     <MenuItem key={g.value} value={g.value}>
                       {g.value} 
                     </MenuItem>
                   )
                 )}
               </Select>
      </ListItem>
    ))}

    
  </List>
  
   const handleChange=(e:any,index:any) => {
console.log(e.target.value)//here I am able to console log just the value how can I bind the user too given the fact that this funciton doesnt accept another parameter

}

Upvotes: 0

Views: 216

Answers (2)

Vivek Sharma
Vivek Sharma

Reputation: 553

Just add index as value as it is uniquely identifiable in the following code -

        {dropdownvalues.map(
                   (g: { value: string},index:number) => (
                     <MenuItem key={g.value} value={index}>
                       {g.value} 
                     </MenuItem>
                   )
                 )}

After that just access your selected user as -

const handleChange = (e:any) => {
const selectedInd = e.target.value;
console.log('index->',selectedInd);
console.log(dropdownvalues[e.target.value]);
}

Upvotes: 1

Goran.it
Goran.it

Reputation: 6299

Simplest way is to extend your handleChange function and call like this:

  // ...
  onChange={(evt) => handleChange(user)}
  // ... And then extend the function:
  const handleChange=(user:any) => {
     console.log(user)
  }
  

Upvotes: 0

Related Questions