Skip to content

Problem in React DropDown list value selection

Iam struggling with a dropdown menu list for my react app.

The problem is, I have a API for which one of the key(key3) has comma(,) seperated values which I want to display in my dropdown list. API response looks like this

{
    "key1": "user",
    "key2": "user",
    "key3": "abc,def,ghi"
}

I have created a reducer for this API response and tried to use .map() function for key3 roughly like this: {this.props.activeRole.key3.map((r)=> <option>{r}</option>)}

but React throws an errors as Cannot read property 'map' of undefined. Where as using the props with .split() works totally fine. Then it makes the redundancy.

<option>{this.props.activeRole.key3.split(",")[0]</option>
<option>{this.props.activeRole.key3.split(",")[1]</option>
<option>{this.props.activeRole.key3.split(",")[2]</option>

Lets say .split() would work as well, so I created a action creator when the option is selected.

const selectedRoleAction = (role) => {
    return {
        type: "ROLE_SELECTED",
        payload: role,
    }
};
export default selectedRoleAction;

But while calling this action reducer there is no change in selected role. How to save the value when the dropdown value changes?

<select className="form-control" onChange={() => this.props.selectedRoleAction((e)=>e.target.value)}>

<option value={this.props.activeRole.role.split(",")[0]>
{this.props.activeRole.role.split(",")[0]}</option>

<option value={this.props.activeRole.role.split(",")[1]>{this.props.activeRole.role.split(",")[1]}</option>

<option value={this.props.activeRole.role.split(",")[2]>{this.props.activeRole.role.split(",")[2]}</option>
</select>

Please help… considering any .map() or .split() scenario, I would take any suggestions.

Answer

In your code the key3 is not a list, its looks like a string so you need to split it before mapping. And in your onChange event, you haven’t passed event(i.e ‘e’) in your callback function.

<select className="form-control" onChange={(e) => this.props.selectedRoleAction((e)=>e.target.value)}>
    {this.props.activeRole.key3.split(',').map((r)=> <option>{r}</option>)}
</select>