Home > Mobile >  onClick DOM event inside an option field doesn't work in the Chrome browser
onClick DOM event inside an option field doesn't work in the Chrome browser

Time:04-18

Here's a breakdown of the problem,

I'm calling the setItem function to set the state of an item in an option field element after an item in the current option is clicked with the onClick event, like so

        <select>
        {items.map((singleItem) => (
          <option key={singleItem.id} onClick={() => setItem(singleItem.name)}>
            {singleItem.name}
          </option>
        ))}
      </select>
      
      <h4>{itemSelected}</h4>

Here's where we have the item state and the setItem function with a useEffect to set the first item name as the default itemSelected

        const [itemSelected, setItem] = useState("")
        useEffect(() => {
            setItem(items[0].name)
        }, [])

This works code works as I expect it to on Firefox but the onClick event in the option field doesn't work in Chrome. How could I go about making it work on the two browsers mentioned above?

Here's a sandbox with running code

https://codesandbox.io/s/stoic-hermann-bw83hj

CodePudding user response:

onClick on <option> element is non-standard, please use onChange on <select> like this:

 <select onChange={(event) => setItem(event.currentTarget.value)}>
        {items.map((singleItem) => (
          <option key={singleItem.id}>
            {singleItem.name}
          </option>
        ))}
      </select>
  • Related