0
votes

I have the following Select from Material UI:

                    <FormControl className='select-form'>
                        <InputLabel id="demo-simple-select-outlined-label">Choose User</InputLabel>
                        <Select
                            labelId="demo-simple-select-outlined-label"
                            id="demo-simple-select-outlined"
                            value={this.state.userId}
                            onChange={this.handleChange}
                            label="choose-user"
                        >
                            {Object.keys(users).map(uId => (  
                                <div key={uId}className='select-menu'>
                                    <img 
                                        src={''}
                                        alt={`Avatar of me`}
                                        className='signin-avatar'
                                    />                                              
                                    <MenuItem value={30}>{users[uId].name}</MenuItem>
                                </div>             
                            ))}
                            <MenuItem value={20}>Hello</MenuItem>
                        </Select>
                    </FormControl>

My handleChange method gets the value of the MenuItem below with the value of 20 when selected. I just used that as a test and the Select and the onChange work just fine. The problem is the div, that get dynamically rendered from the users object. I want to render an avatar and the name of the user in every MenuItem. I have to pack them in a div, because the .map() needs to have one parent item.

I want to pass the value (the user id) of the selected MenuItem to the handleChange method, but all I get is an undefined when a user select is clicked.

How can I pass the value of the select to the onChange method, when the Select items are packed inside a div?

1

1 Answers

1
votes

The correct way is to put your image inside the MenuItem, and you will get the value

  {
    Object.keys(users).map((uId) => (
      <MenuItem value={uId}>
        <img src={''} alt={`Avatar of me`} className="signin-avatar" />
        {users[uId].name}
      </MenuItem>
    ));
  }