katwekibs
katwekibs

Reputation: 1439

How do I completely remove a collapsed section from rendering in React Native's SectionList?

Even when I return null for renderItem or use display: 'none', the container still takes up space and grows to about a quarter of the height it would have had if the section were expanded. What’s the best approach to ensure that the entire container, including any hidden section, doesn’t take up any space when collapsed?" Details:

I’m using SectionList with collapsible sections. When a section is collapsed, I return null for renderItem, but it still leaves an empty gap that grows to about a quarter of the height of the section. I tried using display: 'none', but the container still occupies space. I want to ensure that when a section is collapsed, its container doesn’t reserve any space in the layout.

return (
<View style={styles.container}>
  <SectionList
    sections={sections}
    keyExtractor={(item) => item.id}
    renderItem={({ item, section }: { item: Alert; section: { title: string } }) => {
      if (collapsedSections[section.title]) {
        return null;
      }
      return renderAlert({ item });
    }}
    renderSectionHeader={({ section: { title, data, isArmed, isTriggered } }) => (
      <SectionHeader
        title={title}
        isArmed={isArmed}
        isTriggered={isTriggered}
        isCollapsed={collapsedSections[title]}
        onToggleCollapse={() =>
          setCollapsedSections((prev) => ({
            ...prev,
            [title]: !prev[title],
          }))
        }
        alertCount={data.length}
      />
    )}
    contentContainerStyle={styles.listContainer}
    refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor="#ffd33d" colors={["#ffd33d"]} />}
    ListEmptyComponent={EmptyState}
  />
</View>
);

for each row that was collapsed it still renders the container bellow

<div class="css-view-175oi2r"></div> 

checking css inspection

Upvotes: 0

Views: 22

Answers (1)

imprs
imprs

Reputation: 54

Use Conditional section.data If you don’t want to remove the entire section but just its items:

<SectionList
  sections={sections.map((section) =>
    collapsedSections[section.title] ? { ...section, data: [] } : section
  )}
  keyExtractor={(item) => item.id}
  renderItem={({ item }) => renderAlert({ item })}
  renderSectionHeader={({ section }) => (
    <SectionHeader
      title={section.title}
      isCollapsed={collapsedSections[section.title]}
      onToggleCollapse={() =>
        setCollapsedSections((prev) => ({
          ...prev,
          [section.title]: !prev[section.title],
        }))
      }
      alertCount={section.data.length}
    />
  )}
/>

Why This Works It prevents rendering of section items while still keeping the header.

Upvotes: 1

Related Questions