vito fila vito fila - 4 months ago 22
React JSX Question

How to get the latest value from selected drop down

i have this dropdonw that populates dynamically. when the user selects an item it should set the


with the
. i have written the folllowng code but when i ran this code the
always display the old value not the newly selected value. why is that?

the function in react class is this

ddlProdCatsChanegeEvent: function(e) {


   if (this.state.isMounted)


       var ele = document.getElementById('ddlCategories');

       var seleValue = ele.options[ele.selectedIndex].text;


       alert(this.state.selectedValue);//this always display the old selected value NOT THE new one



the state is this:


   return{data1:[], data2:[], isMounted:false, selectedValue:''}



First of all I will recommend you to make use of refs to access the dom element instead of plain javascript. Not that its necessary but because its JSX syntax and you can use it.

Secondly, setState takes some time to mutate the state and thats the reason you are seeing the previouly selected value because it has not been changed before the alert is being triggered.

Put the alert box in the setState callback method as

this.setState({selectedValue: value}, function(){

Complete code.

var Hello = React.createClass({
   getInitialState: function() {

   return{ selectedValue:''}
   handleChange: function(e) {

        var value = ReactDOM.findDOMNode(this.refs.selectValue).value;
      this.setState({selectedValue: value}, function(){

  render: function() {

    return (<div>
          Hello {}
          <select ref="selectValue" onChange={this.handleChange}>
            <option value="volvo">Volvo</option>
            <option value="saab">Saab</option>
            <option value="mercedes">Mercedes</option>
            <option value="audi">Audi</option>

  <Hello name="World" />,