Dynamically changing number of columns in React Native Flat List

Matthew Chung picture Matthew Chung · May 31, 2017 · Viewed 11.3k times · Source

I have a FlatList where I want to change the number of columns based on orientation. However, I get the red screen when I do this. As per the red screen error message, I'm not quite sure how I should be changing the key prop. Any help is appreciated.

      // dynamically changing number of columns
      const numCols = orientation === constants.PORTRAIT ? 3 : 8

      <FlatList
        keyExtractor={(_, i) => i}
        numColumns={numCols} // assigning the number of columns
        horizontal={false}
        renderItem={({ item }) => <ListItem imageUrl={item.url} />}
      />}

red screen of death

Answer

Greg Billetdeaux picture Greg Billetdeaux · Jun 1, 2017

From the documentation, looks like you should do something like this

key={(this.state.horizontal ? 'h' : 'v')}