Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting react-native FlatList

How can I sort the FlatList by alphabetical order?

export default function PartnersList(props) {
  const { partners, onPartnerDetails } = props;

  return (
    <FlatList
      style={layout.list}
      contentContainerStyle={layout.listContainer}
      numColumns={2}
      data={partners}
      renderItem={({ item }) => (

        ...
like image 523
J.dev Avatar asked Aug 08 '18 09:08

J.dev


People also ask

What is keyExtractor in FlatList?

keyExtractor ​Used to extract a unique key for a given item at the specified index. Key is used for caching and as the react key to track item re-ordering. The default extractor checks item. key , then item.id , and then falls back to using the index, like React does.

What is flat list in React Native?

The FlatList component displays the similar structured data in a scrollable list. It works well for large lists of data where the number of list items might change over time. The FlatList shows only those renders elements which are currently displaying on the screen, not all the elements of the list at once.


1 Answers

Sorting partners would do the trick:

export default function PartnersList(props) {
  const { partners, onPartnerDetails } = props;

  return (
    <FlatList
      style={layout.list}
      contentContainerStyle={layout.listContainer}
      numColumns={2}
      data={partners.sort((a, b) => a.localeCompare(b))}
      renderItem={({ item }) => (

        ...

This works if partners is an array of strings.

If it's an array of objects then you should sort by a string within that object.

for example if partner has a name property, sort must be:

....
data={partners.sort((a, b) => a.name.localeCompare(b.name))}
....
like image 167
StackedQ Avatar answered Oct 16 '22 20:10

StackedQ