React Native apply array values from state as Picker items

jglosbanes picture jglosbanes · Mar 25, 2017 · Viewed 25.7k times · Source

I have an array in my state named Categories.

These are its values: ['Food', 'Home', 'Savings'].

My goal is that I need them to be rendered as Picker.items for my user to select.

How is that possible?

I tried using ListView inside a Picker object, but when I navigate to that page,

AppName stopped Working

prompts.

Answer

Manjeet Singh picture Manjeet Singh · Mar 25, 2017

You don't need to use listview within picker

var options ={
    "1": "Home",
    "2": "Food",
    "3": "Car",
    "4": "Bank",
};

<Picker
    style={{your_style}}
    mode="dropdown"
    selectedValue={this.state.selected}
    onValueChange={()=>{}}>
    {Object.keys(options).map((key) => {
        return (<Picker.Item label={this.props.options[key]} value={key} key={key}/>) //if you have a bunch of keys value pair
    })}
</Picker>

2) When you have an array of values

var options =["Home","Savings","Car","GirlFriend"];

<Picker
    style={{your_style}}
    mode="dropdown"
    selectedValue={this.state.selected}
    onValueChange={()=>{}}> //add your function to handle picker state change
    {options.map((item, index) => {
        return (<Picker.Item label={item} value={index} key={index}/>) 
    })}
</Picker>