Home > Enterprise >  onSelect not triggering for React dropdown
onSelect not triggering for React dropdown

Time:09-24

I am very new to React so I am still learning a lot. No matter what I do, the onSelect just does not seem to work. I made a simple function that it should call. You can tell it's been called via the console.log but in the browser when I look at the console it just does nothing.

Here is the code for the dropdown:

import React,{useState} from 'react';
import SEPractices from "../dummydata/SEPractices"

const optionItems = SEPractices.map((SEPractice) =>
  <option key={SEPractice.practice}>{SEPractice.practice}</option>
);
const Dropdown = () => {

  const handleSelect=(e)=>{
    console.log("Inside");
  }

  return (
    <div>
       <select onSelect={handleSelect}>  
          <option Default hidden>
            Select an SE Practice
          </option>
          {optionItems}
       </select>
    </div>
  )
}
export default Dropdown;

CodePudding user response:

Try using onChange

<select value={selectValue} onChange={handleSelect}>
    <option Default hidden>
       Select an SE Practice
    </option>
    {optionItems}
</select>

And handleSelect like this:

const [selectValue, setValue] = useState("")

cosnt handleSelect = (e) => {
    setValue(e.target.value);
}

CodePudding user response:

<select value={selectValue} onChange={handleSelect}>
    <option value="dummyData">
       Select an SE Practice
    </option>
    {optionItems}
</select>

and don't use the Default and hidden, React will take care of default value why specifying value={selectValue} in element.

Also, we need to pass the value to the <option>, it will track based on the value.

  • Related