Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jeffngugi/0cf7e526f2b70d9c4c22ea0e8e2d7dd5 to your computer and use it in GitHub Desktop.
Save jeffngugi/0cf7e526f2b70d9c4c22ea0e8e2d7dd5 to your computer and use it in GitHub Desktop.
Multi-column SectionList using FlatList

First, let's assemble the data. Say we have two sets of objects: Fruits and Vegetables.

Our sections array would look like this. Note how each section has a data attribute, which is an array of our fruits or vegetables.:

const sections = [
  {
    title: 'Vegetables',
    key: 'vegetables',
    data: [
      {
        name: 'Carrot',
        color: 'Orange'
      },
      {
        name: 'Cabbage',
        color: 'Purple'
      }
    ],
  },
  {
    title: 'Fruits',
    key: 'fruits',
    data: [
      {
        name: 'Apple',
        color: 'Green'
      },
      {
        name: 'Banana',
        color: 'Yellow'
      },
      {
        name: 'Strawberry',
        color: 'Red'
      },
      {
        name: 'Blueberry',
        color: 'Blue'
      }
    ],
  },
]

What we're going to do, is pass that list into a FlatList for each section.

So here's what the final product looks like:

import * as React from "react"
import { Text, View, FlatList, SectionList } from "react-native"

const sections = { ... }

export class MultiColumnExample extends React.Component<{}, {}> {
  renderListItem = ({ item }) => {
    return (
      <View style={{height: 50, width: 100, borderColor: "green", borderWidth: 1 }}>
        <Text>{item.name}</Text>
        <Text>{item.color}</Text>
      </View>
    )
  }
    
  renderSection = ({ section, index }) => {
    return (
      index === 0
        ? <FlatList
            data={item.}
            numColumns={3}
            renderItem={this.renderListItem}
            keyExtractor={this.keyExtractor}
          />
       : null
    )
  }

  renderSectionHeader = ({ section }) => {
    return <Text>{section.title}</Text>
  }

  keyExtractor = (item) => {
    return item.name
  }

  render () {
    return (
      <SectionList
        sections={sections}
        renderSectionHeader={this.renderSectionHeader}
        renderItem={this.renderSection}
      />
    )
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment