I'm making a collapsible list of categories, I need that when click in a item the rest of items are collapse

Viewed 23

I'm build spend management app I have a component that show the categories spend list the category list component is an object with array of category,

the category list component receive by props an object of the type Category

the problem is that being a recursive component a new state is created for each Item in which I can't find a way to control the state

type Category = {
    id: string;
    parent: string;
    name: string;
    children: Category[];
}

type Props = {
  node: Category
}

const CollapsibleList = ({ node }: Props) => {
  const [isVisible, setIsVisible] = useState(false)
  const toggleVisible = () => setIsVisible(!isVisible)

  return (
    <List>
      <Item
        isSelected={isVisible}
        onClick={toggleVisible}>
        {node.name}
      </Item>
      {isVisible && node.children?.map(childrenNode =>
        <CollapsibleList
          key={childrenNode.id}
          node={childrenNode}
        />
      )}
    </List>
  )
}

export default CollapsibleList

I have tried everything any ideas are helpful This is my first post, any criticism is welcome.

I leave a link to codesandbox minimal working sample code

0 Answers
Related