Search code examples
react-nativereact-native-flatlistreact-native-sectionlist

Make VirtualizedList show as Grid


I'm trying to make something like this:

Gird View

The problem: The project was built with immutablejs and according to React Native Docs, I can't use FlatList thus I can't use numColumns props feature of that component. AFAIK, my only choice is to use VirtualizedList as the docs points out, but I can't figure out how to display the cells as a grid as shown above.

I've already tried to add style props in both cell and view wrapper, but none of the code used to align the cells, like the picture I posted, is ignored. In fact it was showing perfect when I was using ScrollView, but due the HUGE lag I'm moving the code to VirtualizedList.

Any help? Anything would be welcome, I already digged a lot on Google but I can't find anything about this.

Some sample code:

      <View>
        <VirtualizedList
          data={props.schedules}
          getItem={(data, index) => data.get(index)}
          getItemCount={(data) => data.size}
          keyExtractor={(item, index) => index.toString()}
          CellRendererComponent={({children, item}) => {
            return (
              <View style={{any flexbox code gets ignored here}}>
                {children}
              </View>
            )}}
          renderItem={({ item, index }) => (
            <Text style={{also here}} key={index}>{item.get('schedule')}</Text>
          )}
        />
      </View>

Solution

  • Answering my own question: I got it working by copying the FlatList.js source code from react-native repo. Here's an example code:

    <VirtualizedList
      data={props.schedules}
      getItem={(data, index) => {
        let items = []
        for (let i = 0; i < 4; i++) {
          const item = data.get(index * 4 + i)
          item && items.push(item)
        }
        return items
      }}
      getItemCount={(data) => data.size}
      keyExtractor={(item, index) => index.toString()}
      renderItem={({item, index}) => {
        return (
          <View key={index} style={{flexDirection: 'row'}}>
            {item.map((elem, i) => (
              <View key={i}>
                <Text key={i}>{elem.get('horario')}</Text>
              </View>
            ))}
          </View>
        )
      }}
    />
    

    The number 4 is for the number of columns. The key parts are in the getItem and adding flexDirection: 'row' at renderItem in the View component.