Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 701
budhavarapu ranga Avatar asked Jun 08 '15 18:06

budhavarapu ranga


People also ask

How do I use onChange in React select?

To handle the onChange event on a select element in React: Set the onChange prop on the select element. Keep the value of the selected option in a state variable. Every time the user changes the selected option, update the state variable.

How does onChange work in React?

An onChange event handler returns a Synthetic Event object which contains useful meta data such as the target input's id, name, and current value. We can access the target input's value inside of the handleChange by accessing e. target. value.

How do you use the select element in React?

How to use HTML <select> tag in ReactJS ? HTML <select> tag is used to create a drop down list with multiple options. The <select> tag is used as outer element and the <option> element is nested within <select> tag for defining options in a list. Approach: To achieve this functionality, we will use “App.


1 Answers

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

like image 151
Crob Avatar answered Oct 08 '22 07:10

Crob