Accordion-Collapse-react-native icon indicating copy to clipboard operation
Accordion-Collapse-react-native copied to clipboard

How to make only one collapse open

Open FatmaMahmoud698 opened this issue 2 years ago • 1 comments

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?

FatmaMahmoud698 avatar Dec 23 '21 14:12 FatmaMahmoud698

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>
  );

Rohan-Rajesh avatar Jan 29 '22 08:01 Rohan-Rajesh