Search code examples
javascripthtmlreactjshtml-select

How do I detect a change in a select element in React?


I have an HTML form with a select dropdown for users to select a color, and I'm trying to detect when a new color has been selected. I've added the onchange attribute with a console.log() function, but nothing is printed to console when I select a new color.

Here's my select element which is contained in the return statement for the form:

<select id="color-selector"
        name="colors"
        onchange={() => console.log("Color has changed")}>
    <option value="red">Red</option>
    <option value="green">Green</option>
    <option value="blue">Blue</option>
    <option value="yellow">Yellow</option>
    <option value="orange">Orange</option>
    <option value="purple">Purple</option>
</select>

I've seen this is possible in vanilla JS from this question, but is there a way to do this by using the onchange attribute in the HTML in React?


Solution

  • You've misspelled onChange. All callbacks in Reactjs are written in camel-case. It's in simple HTML that the attribute is onchange.