Home > Blockchain >  Picker dispalying only last array item
Picker dispalying only last array item

Time:12-16

I have been bashing my skull against the wall for hours trying to make this functional. I am trying to display a 'picker' dropdown list in React Native using the '@react-native-community/picker' module. Here is the code:

import React, { Component } from "react";
import { Button, Dimensions, Image, ImageBackground, Platform, StyleSheet, Text, TextInput, TouchableOpacity, View } from "react-native";

import {Picker} from '@react-native-community/picker';

const deviceWidth = Dimensions.get("window").width;

export default class Results extends Component {
constructor(props) {
  super(props);

  this.state = {
    venues: [{"name": "Carmine's", "id": 0, "name": "Carmines", "id": 1, "name": "Joe's", "id": 2, "name": "Johnny V's", "id": 3, "name": "Cheescake Factory", "id": 4}],
    selectedItem:''
  };
}

  render() {
   return (

      <View style={styles.main}>

       <Picker
       selectedValue={this.state.selectedItem}
       style={{width: deviceWidth, height: 40 }}
       onValueChange={(itemValue, itemIndex) => this.setState({selectedItem: itemValue})}>

       { this.state.venues.map( (v, key)=>{
       return <Picker.Item label={v.name} value={v.id} key={key} />
       }) }

       </Picker>

      </View>

   );  //return
  }  //render

The problem is that the 'picker' control displays however only the 'last' item in the array is displayed ("Cheescake Factory"). As I understand the 'this.state.venues.map' should loop through the array and populate all values into the 'picker' dropdown selection box...

As previously mentioned this is driving me crazy...any suggestions are greatly appreciated! I thank you in advance.

CodePudding user response:

You are very close but it seems like you are trying to loop through an array that only has one object. Try making an individual object for each name and id property and then loop through like you are. This will give you an array of objects. So technically as you have it, you only have an array with one value (an object) so it has a length of 1, which is why you are only returning one value. Once you separate the values into an array of objects you will have length of 5. Good luck!

  this.state = {
    venues: [{"name": "Carmine's", "id": 0}, {"name": "Carmines", "id": 1}, {"name": "Joe's", "id": 2}, {"name": "Johnny V's", "id": 3}, {"name": "Cheescake Factory", "id": 4}],
    selectedItem:''
  };

  • Related