简体   繁体   中英

how to get the id of a selected item using reactjs

My objective is to get the id of a selected item from the dropdown. I could not able to get the id of the respective item.

here is the array looks like

[
{
id: "sdfgh47ddtrgy_8dfstdf"
name: "Orange"
},
{
id: "qwert47ddtrgy_8dfstdf"
name: "Apple"
},
{
id: "ufnhur18fgve_8dfstdf"
name: "Banana"
},
]

I have assigned to the state variable: fruits: []

In dropdown i've maped in this way:

{this.state.fruits.map((fruit) =>
 <MenuItem value={fruit.name} key={fruit.id}>{fruit.name}</MenuItem>
)}

OnChange method:

OnChange = (e)=> {
 let value = this.state.fruits.filter((item) => item.id == e.target.value)
 console.log("Value", value)
}

i'm getting an empty array. Can anyone help me where i'm going wrong?

assuming you use custom select that is mimicking the native select item, and the onChange is on the parent component u should do it like so:

{this.state.fruits.map((fruit) =>
   <MenuItem value={fruit.id/* important*/} key={fruit.id}>{fruit.name} </MenuItem>
)}

the onChange:

OnChange = (e)=> {
   let value = e.target.value
   console.log("Value", value)
}

Change this:

 {this.state.fruits.map((fruit) =>
    <MenuItem value={fruit.name} key={fruit.id}>{fruit.name} 
    </MenuItem>
 )}

TO:

{this.state.fruits.map((fruit) =>
  <MenuItem value={fruit.id} key={fruit.id}>{fruit.name} 
  </MenuItem>
)}

and onChange will be:

OnChange =(e)=> {
 let value = this.state.fruits.filter(item => item.id === e.target.value)
 console.log("Value", value)
}

try this. it should work.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM