Home > Software design >  MUI Collapsible table squashed into one cell when expanded
MUI Collapsible table squashed into one cell when expanded

Time:12-31

I am trying to use MUI table with Collapse to expand/collapse rows. However when using collapse, the the expanded rows are squashed into one cell. How can I align the cells to the parent table?

 export default function App() {
  const [expanded, setExpanded] = useState(false);

  return (
    <Table>
      <TableHead>
        <TableRow>
          <TableCell />
          <TableCell>Header 1</TableCell>
          <TableCell>Header 2</TableCell>
          <TableCell>Header 3</TableCell>
          <TableCell>Header 4</TableCell>
        </TableRow>
      </TableHead>
      <TableBody>
        <TableRow>
          <TableCell onClick={() => setExpanded(!expanded)}>Expand</TableCell>
          <TableCell>A</TableCell>
          <TableCell>B</TableCell>
          <TableCell>C</TableCell>
          <TableCell>D</TableCell>
        </TableRow>
        <Collapse in={expanded} timeout="auto" unmountOnExit>
          <TableRow>
            <TableCell />
            <TableCell>E</TableCell>
            <TableCell>F</TableCell>
            <TableCell>G</TableCell>
            <TableCell>H</TableCell>
          </TableRow>
        </Collapse>
      </TableBody>
    </Table>
  );
};

Removing the Collapse results in the correct format. e.g. current state is: enter image description here

Desired result (after expanding is)enter image description here

CodePudding user response:

The problem is that the <Collapse /> component is a div, and divs can't be wrapped around table rows. You need to make a second table inside the Collapse, and align the cells so they are all the same size.

Codesandbox demo.

  • Related