budhavarapu ranga
budhavarapu ranga

Reputation: 483

React select onChange is not working

JsFiddle : https://jsfiddle.net/69z2wepo/9956/

I am returning a select element in the render function in my react.js code.

But whenever I change the select value, the function in the onChange is not getting triggered.

var Hello = React.createClass({
render: function() {
    return <select id="data-type" onChange={changeDataType()}>
           <option selected="selected" value="user" data-type="enum">User</option>
           <option value="HQ center" data-type="text">HQ Center</option>
           <option value="business unit" data-type="boolean">Business Unit</option>
           <option value="note" data-type="date">Try on </option>
           <option value="con" data-type="number">Con</option>
      </select>
    }
});


React.render(<Hello/>, document.getElementById('container'));

 function changeDataType() {
    console.log("entered");
}

This function is getting triggered only once when the select is loaded and subsequently when I change the value, its not getting triggered.

Upvotes: 11

Views: 44474

Answers (3)

Prateek Arora
Prateek Arora

Reputation: 666

Try this

<select id="data-type" onChange={()=>changeDataType()}>

Upvotes: 0

Michael Parker
Michael Parker

Reputation: 12966

Functions that trigger when a component changes should really be defined inside the component itself.

I recommend defining your function inside of your Hello component, and passing this.changeDataType to your onChange attribute, like so:

var Hello = React.createClass({
changeDataType: function() {
    console.log('entered');
},
render: function() {
    return <select id="data-type" onChange={this.changeDataType}>
           <option selected="selected" value="user" data-type="enum">User</option>
           <option value="HQ center" data-type="text">HQ Center</option>
           <option value="business unit" data-type="boolean">Business Unit</option>
           <option value="note" data-type="date">Try on </option>
           <option value="con" data-type="number">Con</option>
      </select>
    }
});

Here is an updated JSFiddle that produces your expected behavior: https://jsfiddle.net/69z2wepo/9958/

Upvotes: 6

Crob
Crob

Reputation: 15185

onChange takes a function.

You are passing it changeDataType(), which is running the function changeDataType function, and setting onChange to it's return value, which is null.

Try passing the actual function, instead of evaluating the function.

<select id="data-type" onChange={changeDataType}>

Upvotes: 20

Related Questions