Accordion-Collapse-react-native
Accordion-Collapse-react-native copied to clipboard
How to make only one collapse open
I only want one open at a time. I've tried changing states of collapse, but nothing is working. I can open all of the items. Any thoughts?
You have to use isExpanded
as well as onToggle
, the gist is you store the selected index in a state variable and only set expanded of an item if the index is equal to the selected index while looping through, here is an example:
const content: SupportData[] = [
{title: 'Title 1', content: 'Content 1'},
{title: 'Title 2', content: 'Content 2'},
];
const [expandedIndex, setExpandedIndex] = useState<number | null>(0);
return (
<ScrollView contentContainerStyle={styles.container}>
<View>
<View style={styles.body}>
{content.map((item, index) => (
<Collapse
key={index}
style={styles.accordionItem}
isExpanded={index === expandedIndex}
onToggle={() => setExpandedIndex(index)}>
<CollapseHeader style={styles.accordionHeader}>
<Text style={styles.accordionTitle}>{item.title}</Text>
<Image source={DownBlue} style={styles.downArrow} />
</CollapseHeader>
<CollapseBody>
<Text style={styles.accordionContent}>{item.content}</Text>
</CollapseBody>
</Collapse>
))}
</View>
</View>
</ScrollView>
);