'onChange event not triggered in react when using select jsx attribute

I am trying to trigger the onChange event of with select jsx/html attribute. The event doesn't fire, here is the code:

    const [dataType, setDataType] = useState(false);
    const [data, setData] = useState('Art');
    const handleOnChange = (event) => {
        console.log("is 3D? ", dataType);
        console.log("event.target.value ", event.target.value);
        event.target.value === "3D" ? setDataType(true) : setDataType(false);
    }

jsx section:

    <div className="form-group col-md-6 pb-10">
        <select value={data} onChange={handleOnChange} id="category">
            <option value="3D">3D</option>
            <option value="Art">Art</option>
            <option value="Collectibles">Collectibles</option>
            <option value="Photography">Photography</option>
        </select>
    </div>

I am using the latest react version and I followed the doc in this: https://reactjs.org/docs/forms.html#the-select-tag



Solution 1:[1]

You need to actively invoke the handleChange function and pass the event to your handleChange function:

onChange={e => handleOnChange(e)}

The complete example then looks like:

<div className="form-group col-md-6 pb-10">
  <select value={data} onChange={e => handleOnChange(e)} id="category">
    <option value="3D">3D</option>
    <option value="Art">Art</option>
    <option value="Collectibles">Collectibles</option>
    <option value="Photography">Photography</option>
  </select>
</div>

Here's a working CodeSandbox example

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1