Collapse Tab In React Native

I’m using this package react-native-collapsible
and I wanted to behave the closing and opening of tabs like gmail.
Like when I try to open an email, when it has many threads of replies, when you click the first one, it closes the other thread. When you click its thread, it opens it and closes the other thread. I think this is just a simple react/JS issue.

import Collapsible from "react-native-collapsible";

const [collapsedIndex, setCollapsedIndex] = useState([]);

const renderEmailBody = (emailItem) => {
  return (
    <View>
      {emailItem?.body ? (
        <RenderHtml
          contentWidth={width}
          source={{
            html: emailItem?.body,
          }}
          renderersProps={{
            a: {
              onPress: (event, href) => {
                navigate("WebView", href);
              },
            },
          }}
        />
      ) : null}
    </View>
  );
};

const renderEmailData = ({ item, index }) => {
  return (
    <>
      <TouchableOpacity
        activeOpacity={1}
        onPress={() => setCollapsedIndex(index)}
      >
        <Collapsible collapsed={collapsedIndex !== index}>
          {renderEmailBody(item)}
          {item?.attachments
            ? item?.attachments?.map((innerItem, rowIndex) => {
                return <View key={rowIndex?.toString()}>...</View>;
              })
            : null}
        </Collapsible>
      </TouchableOpacity>
    </>
  );
};

const renderEmailDetailsList = () => {
  var data = emailDetailsList;

  return (
    <FlatList
      nestedScrollEnabled
      ref={flatListRef}
      refreshControl={
        <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
      }
      data={data}
      ItemSeparatorComponent={() => <View />}
      renderItem={renderEmailData}
      keyExtractor={(item, index) => index.toString()}
      onEndReachedThreshold={0}
    />
  );
};

>Solution :

i think initial value should be const [collapsedIndex, setCollapsedIndex] = useState(null); not a empty array, also the onpress should be

onPress={() => {
 if (index === collapsedIndex) {
    setCollapsedIndex(null)
 } else {
   setCollapsedIndex(index)
 }
}}

Leave a Reply