11

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.

budhavarapu ranga
  • 483
  • 2
  • 7
  • 15

3 Answers3

20

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

Crob
  • 14,807
  • 3
  • 31
  • 28
  • 3
    is anything async in that code? seems like defining `changeDataType` after setting it as an event listener is a bad idea. Probably should move that method into the Hello object (next to the render method) and use `this.changeDataType`. – pherris Jun 08 '15 at 18:32
  • Instead of using selected attribute of the option tag. You should use pass selected value into select's prop in order to manipulate value easier. https://facebook.github.io/react/docs/forms.html#why-select-value – Phi Nguyen Jun 08 '15 at 19:15
6

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/

Michael Parker
  • 12,724
  • 5
  • 37
  • 58
0

Try this

<select id="data-type" onChange={()=>changeDataType()}>
Prateek Arora
  • 616
  • 8
  • 7