In my react app, I have a select
tag to select some options. The options are fetched from an API and mapped as shown bellow.
<select
id="numberbase__select"
onChange={this.onSelectExistingNumberBase}>
<option selected disabled hidden>Select a number base</option>
{this.props.tenantNumberBases.NumberBases.map((value, index) => {
return (
<option value={value.uuid}>{value.numberBaseName}</option>
);
})}
</select>
To change the value of this, I have used the following helper method.
onSelectExistingNumberBase = (e) => {
this.setState({
existingNumberBase: e.target.value
});
}
This way I can get the uuid
of the mapped array values. But in addition to uuid
, I want to get the numberBaseName
as well. I tried using e.target.id
. But it did't work. I was able to get uuid
because I have added it as the value of option
tag. How can I get more values that uuid
? Please help.
You can find
the selected item by the uuid
easily:
onSelectExistingNumberBase = (e) => {
let item = tenantNumberBases.NumberBases.find(el => el.uuid === e.target.value);
this.setState({
existingNumberBase: item
});
}
Or if the performance is of concern just index the array into an object like:
// This:
let items = [
{ uuid: 1, numberBaseName: "a" },
{ uuid: 2, numberBaseName: "b" }
]
// To This:
let itemsIndexedByUUID = {
1: { uuid: 1, numberBaseName: "a" },
2: { uuid: 2, numberBaseName: "b" }
}
Then your handler will be simpler:
onSelectExistingNumberBase = (e) => {
this.setState({
existingNumberBase: itemsIndexedByUUID[e.target.value]
});
}
There might be few ways to achieve this. But I'll post here the solution that helped me.
First in select option, code like this.
<select
onChange={this.onSelectExistingNumberBase}>
<option selected disabled hidden>Select a number base</option>
{this.props.tenantNumberBases.NumberBases.map((value, index) => {
return (
<option value={value.uuid} id={value.numberBaseName}>{value.numberBaseName}</option>
);
})}
</select>
Then in the onChange helper method I followed something like following.
onSelectExistingNumberBase = (e) => {
this.setState({
existingNumberBase: e.target.value,
numberBaseName: e.target.options[e.target.selectedIndex].text,
});
}
I was able to get options and then the value inside the option tag using selected index. I hope this will help someone who has the same problem.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.