Dynamically changing number of columns in React Native Flat List

Viewed 19475

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

7 Answers

I did it using key

    numColumns = {this.state.columnCount}
    key={this.state.columnCount}

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.

In Hooks

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

<FlatList
key={numCols}
numColumns={numCols}
...
/>
<FlatList
         data={props.localFolders}
         style={{ width: "100%" }}
         numColumns={4}
         key={4}
         renderItem={({ item }) => <LocalFolder {...item} />}
         keyExtractor={(item) => item.id.toString()}
/>

works for me

If you need to make your app responsive when is landscape mode, try this:

     const {height, width} = useWindowDimensions();
     const isLandscape = width > height;

     <FlatList
     numColumns={Number(isLandscape) + 1}
     keyExtractor={item => item.id}
     key={Number(isLandscape)}
     ...

This will convert boolean into number. Note useWindowDimensions is imported from react-native.

Related