Home > Net >  getting the ID when user is selected in dropdown in react
getting the ID when user is selected in dropdown in react

Time:07-05

I have a dropdown list in react. in which username is getting displayed. my requirement is to get id instead of username when user select any value.

enter image description here

I have below code for that.

                            <select
                                onChange={(e) => selectedUser(e)}
                                className=" form-select-control">
                                <option value="">Please select the user</option>
                                {active &&
                                    users.map((user: any) => (
                                        <option>{user.displayName}</option>
                                    ))}
                            </select>



  const selectedUser = (e: any) => {
        setUser(e.target.value);
    };

on dropdown I am getting data from API. below is the data.

enter image description here

I am getting ID along with displayName(username) from API. my question is under selectedUser method how can I get ID for selected user. is there any other way as well?

CodePudding user response:

You can write the code something like this

                        <select
                            onChange={(e) => selectedUser(e)}
                            className=" form-select-control">
                            <option value="">Please select the user</option>
                            {active &&
                                users.map((user: any) => (
                                    <option id={user.id}>{user.displayName}</option>
                                ))}
                        </select>



  const selectedUser = (e: any) => {
    setUser(e.target.id);
};

CodePudding user response:

There are several ways to achieve this.

You need to define a key if you create DOM elements with React when you iterate through an array with .map() anyway (else you'll get a warning in the console of your browser). You can use the key to get the user.id:

<select onChange={(e) => selectedUser(e)} className=" form-select-control">
    <option value="">Please select the user</option>
    {active &&
        users.map((user: any) => (
            <option key={user.id}>{user.displayName}</option>
        ))}
</select>;

const selectedUser = (e: any) => {
    setUser(e.target.key);
};

You could also save the user.id in id={user.id} and grab it via e.target.id.

  • Related