Faisal Ahmed
Faisal Ahmed

Reputation: 35

Bind Picker.Item 'label' from an array in React Native

I'm a newbie and want to know how can I pick 'label' of 'Picker.Item' from an array. I have an array 'Account[]' each of its element is an object of 'AccountSchema' shown below
Code For Dropdown List

<Picker
style={{width:'70%'}}
selectedValue={this.state.PickerValue}
onValueChange={(itemValue,itemIndex) =>this.setState({PickerValue:itemValue})}>
                   <Picker.Item label="Select Name of A/C" value=""/>
                   <Picker.Item label="Salary A/C" value="salary" />
                   <Picker.Item label="Rent A/C" value="Rent"/>
</Picker>

Database (Schema) & Method to get all Accounts

export const AccountSchema = {
name: ACCOUNT_SCHEMA,
primaryKey: 'id',
properties: {
    id: 'int',    // primary key
    name: { type: 'string', indexed: true },
    type: 'string',
    balance: 'int',
    note:'string',
    creationDate: 'date',
}
};

export const queryAllAccounts = () => new Promise((resolve, reject) => {
    Realm.open(databaseOptions).then(realm => {
        let allAccounts = realm.objects(ACCOUNT_SCHEMA);
        resolve(allAccounts);
    }).catch((error) => {
         reject(error);
    });;
});

In dropdown list I want to show Account name, So its necessary to show 'account.name' in 'label' foreach.

Upvotes: 1

Views: 2432

Answers (1)

Roy Wang
Roy Wang

Reputation: 11260

You can map your data to the Picker.Item component:

  <Picker
    style={{ width: '70%' }}
    selectedValue={this.state.PickerValue}
    onValueChange={(itemValue, itemIndex) => this.setState({ PickerValue: itemValue })}
  >
    {accounts.map(acct => <Picker.Item key={acct.id} label={acct.name} value="" />)}
  </Picker>;

Upvotes: 1

Related Questions