React select onChange not working

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

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

But whenever I change the select value, the function in onChange does not start.

 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 only runs once when the selection is loaded, and then when I change the value, it does not start.

+5
source share
2 answers

onChange performs a function.

You pass it to changeDataType() , on which the changeDataType function is changeDataType , and set the onChange parameter onChange return value that is null.

Try passing the actual function instead of evaluating the function.

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

+11
source

The functions that are triggered when a component changes must be really defined inside the component itself.

I recommend defining your function inside your Hello component and passing this.changeDataType your onChange attribute, for example:

 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 the updated JSFiddle that gives the expected behavior: https://jsfiddle.net/69z2wepo/9958/

+5
source

All Articles