Search code examples
arraysobjectreact-nativereact-native-flatlist

React Native FlatList rendering only 1 object


I have been struggling with rendering this object in a FlatList. Please can someone help me. There's 2 objects in the FlatList but it is only rendering 1 object for some reason

The peopleArray

Const peopleArray = [
          "id": "U1600078348291",
          "People": [
            {
              "number": "4",
              "value": "Jack Sparrow",
            },
            {
              "number": "6",
              "value": "Daniel Roberts",
            },
          ],
        ]

I have tried the following things and it isn't working

First Try

<FlatList
      data={Object.keys(obj)}
      keyExtractor={(item, index) => item.index}
 />

Second Try

FlatList
      data={peopleArray}
      keyExtractor={(item) => item.id}
      renderItem={({item})=><Text>{item.index.key.value}</Text>}
/>

Third Try This works but only shows one out of the two objects

<FlatList
      data={peopleArray}
      keyExtractor={(item) => item.id}
      renderItem={({item})=>{<Text>{item[index].value}</Text>}}
/>

Fourth Try

<FlatList
      data={peopleArray}
      keyExtractor={(item) => item.id}
      renderItem={({item})=>{<Text>{item.value}</Text>}}
/>

My Code:

const People = (props) => {
  const peopleArray = props.navigation.getParam('people')
  const renderPeople = ({item}) => {
    return <Text>{item[index].value}</Text>
  };
  return (
    <FlatList
      data={peopleArray}
      keyExtractor={(item) => item.id}
      renderItem={renderPeople}
    />
  );
};

Solution

  • According to "My Code" section you want the list to be created out of "People". your FlatList should look something like this:

    <FlatList
         data={peopleArray}
         keyExtractor={(item) => item.id}
         renderItem={renderPeople}
     />
    

    And renderPeople like this:

    const renderPeople = ({item}) => (
               <View>
                   {
                     item.People.map(person => <Text>{person.value}</Text>)
                   }
               </View>
    )