I need a function at every here is it. i want to access option value.
const region = ['Africa','America','Asia','Europe','Oceania'];
<div className="options">
<select>
<option>Select a Region</option>
{region.map((nameOfRegion) => {
return <option onClick={() => requestRegion(nameOfRegion)}>
{nameOfRegion}
</option>
})}
</select>
this function is not logging options
const requestRegion = (region) => {
console.log(region)
}
I need a function at every here is it. i want to access option value.
const region = ['Africa','America','Asia','Europe','Oceania'];
<div className="options">
<select>
<option>Select a Region</option>
{region.map((nameOfRegion) => {
return <option onClick={() => requestRegion(nameOfRegion)}>
{nameOfRegion}
</option>
})}
</select>
this function is not logging options
const requestRegion = (region) => {
console.log(region)
}
Share
Improve this question
asked May 8, 2021 at 9:45
Kamlesh SharmaKamlesh Sharma
391 silver badge5 bronze badges
0
3 Answers
Reset to default 4Use onChange
event on the <select>
:
const requestRegion = (event) => {
console.log(event.target.value);
};
return (
<div className="options">
<select onChange={requestRegion}>
<option>Select a Region</option>
{
region.map((nameOfRegion) => (<option>{nameOfRegion}</option>))
}
</select>
</div>
Because neither the onSelect()
nor onClick()
events are supported by the option
tag. So you can use onChange
in select
tag in this case:
const onChange =(e) => {
console.log(e.target.value);
}
<select name="select" onChange = {onChange}>
<option>Select a Region</option>
{region.map((nameOfRegion, i) => {
return (
<option key={i}>
{nameOfRegion}
</option>
);
})}
</select>
Note: you need add key in child tag when using map
You should use an onChange
handler on the select
element, and get the value from the change event:
const Demo = ({ regions }) => {
const requestRegion = e => {
console.log(e.target.value)
}
return (
<select onChange={requestRegion}>
<option>Select a Region</option>
{regions.map(region => (
<option key={region}>{region}</option>
))}
</select>
)
}
const regions = ['Africa','America','Asia','Europe','Oceania']
ReactDOM.render(
<Demo regions={regions} />,
root
)
<script crossorigin src="https://unpkg./react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg./react-dom@17/umd/react-dom.development.js"></script>
<div id="root"></div>