Attila
Attila

Reputation: 1177

FlatList does not pass through 0 or null into renderItem prop

If I try to render a FlatList like so:

<View>
   <FlatList
     numColumns={2}
     data={[1, 0, 3, null]}
     renderItem={(itemData, idx) => <Text key={idx}>{itemData.item}</Text>}
     horizontal={false}
   />
</View>

The only thing returned would be 1 and 2 (except they take up space in the row/column as if the other values had rendered as well–they stack up in a column). I have no access to the 0 value or the null value (so I can't conditionally render something else, i.e. return itemData.item || 'No Data'.

If I try this (with slightly less props):

<View>
    <FlatList
      data={[1, 0, 3, null]}
      renderItem={(itemData, idx) => <Text key={idx}>{itemData.item}</Text>}
    />
</View>

I get an error Invariant Violation: No item for index 2.

Is there a solution besides looping through the data beforehand and replacing all 0's with a string "0" and all nulls, undefined, empty strings etc. with a string "null" and conditionally rendering with that: return itemData.item !== 'null' ? itemData.item || 'No Data'

Upvotes: 1

Views: 1529

Answers (1)

soutot
soutot

Reputation: 3671

It looks like when you try to access itemData.0 it understands as false instead of number 0, the same logic looks to be applied when trying to access itemData.null value.

If you add a console.log to your renderItem, you can confirm if what I said is correct

renderItem={(itemData, idx) => {
  console.log('Trying to render item: ', idx);
  return <Text key={idx}>{itemData.item}</Text>;
}}

Supposing this is the case, then you can achieve what you want by something like this:

renderItem={(itemData, idx) => itemData.item && <Text key={idx}>{itemData.item}</Text>}

Hope it helps

Upvotes: 1

Related Questions