Skip to content

Instantly share code, notes, and snippets.

@peterpme
Created December 16, 2022 18:03
Show Gist options
  • Save peterpme/b818eca2b7faf0e06f2466ab3e84db62 to your computer and use it in GitHub Desktop.
Save peterpme/b818eca2b7faf0e06f2466ab3e84db62 to your computer and use it in GitHub Desktop.
SectionList expand/collapse example
import { useState } from 'react';
import {
Text,
View,
StyleSheet,
SectionList,
SafeAreaView,
StatusBar,
Pressable,
} from 'react-native';
const DATA = [
{
title: 'Main dishes',
data: ['Pizza', 'Burger', 'Risotto'],
},
{
title: 'Sides',
data: ['French Fries', 'Onion Rings', 'Fried Shrimps'],
},
{
title: 'Drinks',
data: ['Water', 'Coke', 'Beer'],
},
{
title: 'Desserts',
data: ['Cheese Cake', 'Ice Cream'],
},
];
export default function App() {
const [expandedSections, setExpandedSections] = useState(new Set());
const handleToggle = (title) => {
setExpandedSections((expandedSections) => {
// Using Set here but you can use an array too
const next = new Set(expandedSections);
if (next.has(title)) {
next.delete(title);
} else {
next.add(title);
}
return next;
});
};
return (
<SafeAreaView style={styles.container}>
<Text style={{ marginBottom: 12 }}>
Simple example of an expand/collapse SectionList. Tap any of these
sections to expand.
</Text>
<SectionList
sections={DATA}
extraData={expandedSections} // extraData is required to re-render the list when expandedSections changes
keyExtractor={(item, index) => item + index}
renderItem={({ section: { title }, item }) => {
// check to see if the section is expanded
const isExpanded = expandedSections.has(title);
//return null if it is
if (!isExpanded) return null;
return <Item title={item} />;
}}
renderSectionHeader={({ section: { title } }) => (
<Pressable onPress={() => handleToggle(title)}>
<Text style={styles.header}>{title}</Text>
</Pressable>
)}
/>
</SafeAreaView>
);
}
// Implementation details below. Nothing to worry about!
const Item = ({ title }) => (
<View style={styles.item}>
<Text style={styles.title}>{title}</Text>
</View>
);
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: StatusBar.currentHeight,
marginHorizontal: 16,
},
item: {
backgroundColor: '#f9c2ff',
padding: 12,
marginVertical: 4,
},
header: {
fontSize: 24,
backgroundColor: '#fff',
},
title: {
fontSize: 18,
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment