Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically changing number of columns in React Native Flat List

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

like image 472
Matthew Chung Avatar asked May 31 '17 18:05

Matthew Chung


People also ask

How to optimize a large list of items on FlatList?

Use getItemLayout​ If all your list item components have the same height (or width, for a horizontal list), providing the getItemLayout prop removes the need for your FlatList to manage async layout calculations. This is a very desirable optimization technique.

What is the difference between MAP and FlatList in react native?

Displaying data using map or other loop methods may give you flexibility to customize the list the way you want, but as the amount of data grows, you also need to take extra care of the bulk data you render on the visible screen. FlatList makes handling complex and large amounts of list data easy and effortless.

What is flat list in react?

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.


4 Answers

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

key={(this.state.horizontal ? 'h' : 'v')}
like image 106
Greg Billetdeaux Avatar answered Sep 22 '22 20:09

Greg Billetdeaux


I did it using key

    numColumns = {this.state.columnCount}
    key={this.state.columnCount}
like image 41
krish Avatar answered Sep 20 '22 20:09

krish


Pass a changing value to the FlatList itself. It has nothing to do with the keyExtractor or the key attrbibute in renderItem methods:

<FlatList key={changingValue} .. /> 

should solve it.

like image 43
SupaMario Avatar answered Sep 22 '22 20:09

SupaMario


In Hooks

const [numCols, setColumnNo] = useState(0);

<FlatList
key={numCols}
numColumns={numCols}
...
/>
like image 20
Aayush Bhattacharya Avatar answered Sep 23 '22 20:09

Aayush Bhattacharya