0
const data = [
   {
    "name": "AAXx",
    "number" "111111"
    "type": "employee",
   },
   {
    "name": "bbbs",
    "number" "2222"
    "type": "employee",
   },
   {
    "name": "xxx",
    "number" "3333"
    "type": "students",
   },
]

<FlatList
            data={data}
            keyExtractor={item => item.number }
            renderItem={({ item }) => <Text> {item.name}</Text>
/>

Current result

AAXx

bbbs

xxx

Expected Result

employe

AAXx

bbbs

students

xxx

I already try ListHeaderComponent but i want this on the base of key (type). How can i achieve expected result with this data set.

Thanks.

osama somy
  • 385
  • 5
  • 16

1 Answers1

1

You need a SectionList rather than a FlatList.

And you also need to group your data into sections so that SectionList can understand how it should list items under which sections.

const DATA = [
  {
    title: 'employee',
    data: [{
      name: 'AAXx',
      number: '111111',
    },
    {
      name: 'bbbs',
      number: '2222',
    }],
  },
  {
    title: 'students',
    data: [{
      name: 'xxx',
      number: '3333',
    },
    ],
  },
];

const Item = ({ title }) => (
  <View style={styles.item}>
    <Text style={styles.title}>{title}</Text>
  </View>
);

const App = () => (
  <SafeAreaView style={styles.container}>
    <SectionList
      sections={DATA}
      keyExtractor={(item, index) => item.number}
      renderItem={({ item }) => <Item title={item.name} />}
      renderSectionHeader={({ section: { title } }) => (
        <Text style={styles.header}>{title}</Text>
      )}
    />
  </SafeAreaView>
);

https://snack.expo.io/@nicefella82/sectionlist-example

Nostromo
  • 959
  • 2
  • 7
  • 25
  • 1
    How can i convert my data into sections? like yours. – osama somy Sep 03 '20 at 19:40
  • This is another subject which is to group an array of objects by key. Take a look : https://stackoverflow.com/questions/40774697/how-to-group-an-array-of-objects-by-key – Nostromo Sep 03 '20 at 19:43
  • @Nostromo please here is my issue check it https://stackoverflow.com/questions/75053910/how-to-set-header-in-alphabetic-way-in-react-native –  Jan 09 '23 at 09:59