skip to Main Content

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?

2

Answers


  1. import React, {
      FormEvent,
      FormEventHandler,
      SelectHTMLAttributes,
      useState,
    } from "react";
    
    export default function Home() {
      const [color, setColor] = useState("");
      function colorChange(e) {
        setColor(e.target.value);
        console.log(e.target.value);
      }
      return (
        <div>
          <select name="color" id="color" value={color} onChange={colorChange}>
            <option value="">Select option</option>
            <option value="red">Red</option>
            <option value="blue">Blue</option>
            <option value="green">Green</option>
          </select>
        </div>
      );
    }
    
    Login or Signup to reply.
  2. You’ve misspelled onChange. All callbacks in Reactjs are written in camel-case. It’s in simple HTML that the attribute is onchange.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search