vito fila vito fila - 2 months ago 12
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

state

'selectedValue'
with the
'SelectedValue'
. i have written the folllowng code but when i ran this code the
alert()
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;

       this.setState({selectedValue:seleValue});

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

   }

},


the state is this:

getInitialState:function(){

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

}

Answer

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(){
        alert(this.state.selectedValue);
      });

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(){
        alert(this.state.selectedValue);
      });

    },
  render: function() {

    return (<div>
          Hello {this.props.name}
          <div>
          <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>
          </select>
          </div>
          </div>
  )}
});

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);

JSFIDDLE