Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a React Native FlatList with two completely different arrays of data

I have two arrays, one for products, and one for supervisors. Obviously, both have very different types of data. I want to create a scrollable list that will display all of the products followed by all of the supervisors using a single scrolling list. Is this possible with React Native's FlatList? If so, or if not, how can I go about doing this?

I can currently render a single data array as follows:

<FlatList
    data={this.state.products}
    renderItem={this.renderItem}
/>

But, how can I append the supervisors data to the end of this list? Obviously, because the data is quite different between the two arrays I cannot simply merge the arrays and or the same renderItem function.

How can I display two completely different types of data one after the other in the same scrollable list?

like image 238
kojow7 Avatar asked Dec 11 '22 06:12

kojow7


1 Answers

You can merge your data together and use single FlatList with a single renderItem prop. Without a sample of your data its a little guessing game but below is an example how you can do.

Example

Let's assume you have data structure like below.

const Products = [
  {
    id: 1,
    name: 'Product 1'
  },
  {
    id: 2,
    name: 'Product 2'
  },
  {
    id: 3,
    name: 'Product 3'
  },
  {
    id: 4,
    name: 'Product 4'
  },
];

const Supervisors = [
  {
    belongsToPruduct: 1,
    name: 'SuperVisor 1' 
  },
  {
    belongsToPruduct: 3,
    name: 'SuperVisor 2' 
  },
  {
    belongsToPruduct: 2,
    name: 'SuperVisor 3' 
  },
  {
    belongsToPruduct: 4,
    name: 'SuperVisor 4' 
  }
];

And let's assume you render Products in a FlatList. You can do something like below in your renderItem function

renderItem = ({ item }) => {
  const superviors = Supervisors.filter((supervisor) => supervisor.belongsToPruduct === item.id)
  return (
    <View style={styles.productContainer}>
      <Text style={styles.productName}>{item.name}</Text>
        <View style={styles.supervisorsContainer}>
          {
            superviors.map((supervisor) => <Text style={styles.supervisorName}>{supervisor.name}</Text>)
          }
        </View>
    </View>
  )
}

UPDATE

Referring to your comment I think then you can get use of SectionList rather than FlatList

<SectionList 
   renderSectionHeader={({ section: { title } }) => <Text style={{ fontWeight: 'bold' }}>{title}</Text>} 
   sections={[ 
     { title: 'Products', data: Products, renderItem: ({ item, index, section: { title, data } }) => <Text>{item.name}</Text> }, 
     { title: 'Supervisors', data: Supervisors, renderItem: ({ item, index, section: { title, data } }) => <Text>{item.name}</Text>}, 
    ]} 
   keyExtractor={(item, index) => item.name + index} 
 />
like image 110
bennygenel Avatar answered Dec 28 '22 06:12

bennygenel