1

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)
}
0

3 Answers 3

4

Use 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>

Edit stoic-cohen-d7cyj

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>

<div id="root"></div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.