Python
Python

Reputation: 609

How to make changes by using onChange using <select> in React?

I'm making an app that uses a dropdown menu like:

            <select name="color">
              <option value="red" onChange={this.func}>Red</option>
              <option value="blue" onChange={this.func}>
                Blue
              </option>
            </select>

However, the onChange function is not working. The function given is:

  func = () => {
    console.log("Color");
  };

I'm wondering why is this not working? What should be done to make it work?

Thanks in advance.

Upvotes: 0

Views: 205

Answers (1)

NickG
NickG

Reputation: 611

Your code does not work, because selects fire onChange events, and options don't. You need move the onChange event handling to the <select/>:

 <select name="color" onChange={this.func}>
   <option value="red">Red</option>
   <option value="blue">Blue</option>
 </select>

// and for your func:
func = (event) => {
  //event.target.value contains the selected option value, e.g. "red"
  console.log("Color: ", event.target.value);
};

Upvotes: 1

Related Questions