React select onChange is not working

42.7k Views Asked by At

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.

3

There are 3 best solutions below

2
On BEST ANSWER

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}>

1
On

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/

2
On

Try this

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