1

I am new to learn react native. I want to get selected value from dropdown in react-native.

my constructor

constructor(props){
      super(props);
      this.state = ({       
        PickerSelectedVal : ''
      })
}

in render

render(){
      <Dropdown                 
                label="Select"
                options={["Op1","Op2"]}                     
                selectedValue={this.state.PickerSelectedVal}
                onSelect={(obj)=>this.changedemo({obj})}
      />
}

in function

 changedemo= (ob)=>{
      this.setState({PickerSelectedVal : ob});
      alert("Selected country is : " +ob.PickerSelectedVal);
      console.log(this.state.PickerSelectedVal);
      if (this.state.PickerSelectedVal === 1) {
          alert("Selected value is : " +ob.PickerSelectedVal);
      } 
      if(this.state.PickerSelectedVal === 0) {
alert("Selected value is : " +ob.PickerSelectedVal);
      }

  }

I have tried many times. I want to get selected value from dropdown alert is also showing but it prints. Selected value is:undefined.

2 Answers 2

1

setState is a async process so when you are printing it by that time the state is not yet set. Add This

this.setState({PickerSelectedVal : ob},()=>{console.log(this.state.PickerSelectedVal)});
Sign up to request clarification or add additional context in comments.

1 Comment

thank you! I can show in console. but in alert not showing value. it shows undefined.
0

your changedemo function must be like following;

  changedemo= (ob)=>{
      this.setState({PickerSelectedVal : ob.value});
      alert("Selected country is : " +ob.value);
      console.log(ob.value);
      // rest of the code
  }

18 Comments

thanks for reply! alert("Selected country is : " +this.state.PickerSelectedVal); but it shows only Selected Country is : blank value not print any value.
on first line of changedemo function start add following line alert(ob); and comment here output.
which package you are using for dropdown?
I have added alert(ob); it show output : [object Object]. I can show object in log also output: { obj: { index: '0', value: 'Op1' } }
ok so now try this alert("Selected country is : " +ob.value);
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.