How to get the last value from the selected dropdown

I have this dropdonw that populates dynamically. when the user selects an item he should set

condition 'selectedValue'

using 'selectedValue'

. i wrote the folllowng code, but when i run this code it alert()

always displays the old value, not the new selected value. Why is this?

react class function is

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 as follows:

getInitialState:function(){

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

}

      

+1


source to share


2 answers


First . I recommend you use refs

dom to access element instead of plain javascript. Not that it is necessary, but because its JSX syntax and you can use it.

Second , setState takes some time to change state and this is the reason why you see the previously selected value because it was not changed before the alert was fired.

Place the alert box in the setState callback method like

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

+2


source


UPDATE Take a look at this example

React strongly discourages direct manipulation of the DOM or with methods such as getElementById()

. So write a solution wrt your code will be wrong. Instead, I'm going to give you an example to help you understand how to react to actions and how to implement what you intend.

You can always use ReactDOM, but that would be overkill. Instead, you can use event.target.value

to get the updated value from the field directly <select />

. How you fill in the field is <select />

entirely up to you. I prefer using s Array.map()

to iterate over the data and return a set of <option />

s.

Also note that () => {}

is is an arrow function from es6. You can replace this with es5 function() {}

at any time.



import React from 'react';

class SelectExample extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedValue: 0
    }
    this.updateValue = this.updateValue.bind(this);
  }

  updateValue(value) {
    this.setState({
      selectedValue: value
    }, () => alert(value));
  }

  render() {
    const dataSet = [1, 2, 3, 4];
    return (
      <div>
        <select value={this.state.selectedValue} onChange={(e) => this.updateValue(+e.target.value)}>
          <option value={0}>Default Value</option>
          {
            dataSet.map((item, idx) => <option value={item} key={idx}>{"Example " + item}</option>)
          }
        </select>
      </div>
    )
  }
}

      

This code is untested. Therefore, you can clean up some errors, if any. You're going completely against the React use case by using document.getElementById

. Please change your code to what I posted here.

Also read Controlled Component

0


source







All Articles