In ReactJS, onClick event does not work in Google Chrome browser but works fine in Firefox. When I add onClick event with arrow function in option tag inside select it's not work in any situation in Google Chrome.
<select>
{data.map( (item) => {
return(
<>
<option onClick={()=>alert('Test')} value={item.name} key={item.id}>{item.name}</option>
</>
)
})}
</select>
I actually need to call an ES6 arrow function with some parameter inside option tag
<select>
{data.map( (item) => {
return(
<>
<option onClick={()=>LoadNew(item.id)} value={item.name} key={item.id}>{item.name}</option>
</>
)
})}
</select>
This is working fine in Firefox but doesn't work in the Google Chrome browser. Any idea how can I solve this problem?
CodePudding user response:
Actually, you need to pass the onChange
props to the select
tag, and from there you can access the value.
<select onChange={(e)=>console.log(e.target.value)}>
{data.map( (item) => {
return(
<>
<option value={item.name} key={item.id}>{item.name}</option>
</>
)
})}
</select>
CodePudding user response:
So I came up with a brute force approach. since you need to pass the id of the item to a LoadNew function
export default function App() {
let data = [
{ name: "Love", id: 1 },
{ name: "labs", id: 2 }
];
return (
<div className="App">
<select
onChange={(e) => {
let item= data.filter((val) => val.name == e.target.value);
LoadNew(item.id)
}}
>
{data.map((item) => {
return (
<>
<option value={item.name} key={item.id}>
{item.name}
</option>
</>
);
})}
</select>
</div>
);
}
You can get the selected value by placing an onChange event Listener on the select tag. We then filter the data to get the specific item, after we pass the item's id to the function.