First, let's assemble the data. Say we have two sets of objects: Fruits and Vegetables.
const fruits = [
{
name: 'Apple',
color: 'Green'
},
{
name: 'Banana',
color: 'Yellow'
},
{
name: 'Strawberry',
color: 'Red'
},
{
name: 'Blueberry',
color: 'Blue'
}
]
const vegetables = [
{
name: 'Carrot',
color: 'Orange'
},
{
name: 'Cabbage',
color: 'Purple'
}
]
For a regular section list with no columns, 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 plainOldsections = [
{
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'
}
],
},
]
But for our multi-colum section list, we have to get a bit tricky:
const multiColumnSections = [
{
title: 'Vegetables',
key: 'vegetables',
data: [
{
list: [
{
name: 'Carrot',
color: 'Orange'
},
{
name: 'Cabbage',
color: 'Purple'
}
]
}
]
},
{
title: 'Fruits',
key: 'fruits',
data: [
{
list: [
{
name: 'Apple',
color: 'Green'
},
{
name: 'Banana',
color: 'Yellow'
},
{
name: 'Strawberry',
color: 'Red'
},
{
name: 'Blueberry',
color: 'Blue'
}
],
}
]
},
]
Note how the data
attribute in each section is now an array with one item in it. That one item is just an object with a list
attribute which contains our actual data.
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 = [
{
title: "Vegetables",
key: "vegetables",
data: [
{
key: "vegetables",
list: [
{
name: "Carrot",
color: "Orange",
},
{
name: "Cabbage",
color: "Purple",
},
],
},
],
},
{
title: "Fruits",
key: "fruits",
data: [
{
key: 'fruits',
list: [
{
name: "Apple",
color: "Green",
},
{
name: "Banana",
color: "Yellow",
},
{
name: "Strawberry",
color: "Red",
},
{
name: "Blueberry",
color: "Blue",
},
],
},
],
},
]
export class MultiColumnExample extends React.Component<{}, {}> {
renderSection = ({ item }) => {
return (
<FlatList
data={item.list}
numColumns={3}
renderItem={this.renderListItem}
keyExtractor={this.keyExtractor}
/>
)
}
renderSectionHeader = ({ section }) => {
return <Text>{section.title}</Text>
}
renderListItem = ({ item }) => {
return (
<View style={{height: 50, width: 100, borderColor: "green", borderWidth: 1 }}>
<Text>{item.name}</Text>
<Text>{item.color}</Text>
</View>
)
}
keyExtractor = (item) => {
return item.name
}
render () {
return (
<SectionList
sections={sections}
renderSectionHeader={this.renderSectionHeader}
renderItem={this.renderSection}
/>
)
}
}
Clever idea with the embedded single object in the
data
array. Thanks for posting.