Expand collapse (material-ui) only one at a time - React

Viewed 381

I have table that I can expand Collapse material-ui. Everything is worked perfectly.

But there is one thing I want to update that when I click to expand there is only one expand collapse opened at a time.

const InvoiceInfo = ({el}) => {

const [open, setOpen] = React.useState(false)
}

function handleExpand() {
    setOpen(!open)
  }

return (
<>
<TableRow key={el.id}>
    <TableCell>
       {el.name}
    </TableCell>
    <TableCell>
        <IconButton onClick={handleExpand}>
                {open ? (
                  <KeyboardArrowUp fontSize="large" />
                ) : (
                  <KeyboardArrowDown fontSize="large" />
                )}
         </IconButton>
    </TableCell>
</TableRow>
{
<TableRow>
    <Collapse in={open} timeout="auto" unmountOnExit>
        <div>
           EXPAND ROW
        </div>
    </Collapse>
</TableRow>
}
</>
)

Above is my code looks like.

Any advice is very meaningful to me. Thank you so much.

1 Answers

You can use a simple state based on the index of an array or a given number / value:

const [isOpenCollapse, setIsOpenCollapse] = useState(null);

const handleOpen = (clickedIndex) => {
  if (isOpenCollapse === clickedIndex) {
    setIsOpenCollapse(null);
  } else {
    setIsOpenCollapse(clickedIndex);
  }
};

[...]

return (
  <List>
    {arr.map((elm, index) => {
      return (
        <>
          <ListItem key={elm.ID} onClick={() => handleOpen(index)} id="listItem">
            {isOpenCollapse === index ? <ExpandLess /> : <ExpandMore />}
            <Box>
              <Typography>{elm.label}</Typography>
            </Box>
          </ListItem>
          <Collapse in={isOpenCollapse === index} timeout="auto" unmountOnExit>
            <p>PUT SOMETHING HERE</p>
          </Collapse>
        </>
      );
    })}
  </List>;
)
Related