Search code examples
javascriptreactjsmaterial-uimui-datatable

MUI-Datatable: TableHead inside Expandable Row keeps on repeating for every row of the table and table does not center


How do I solve this? Table headings just keep on repeating for every row in the table as seen in the picture below. Also, the table is always at the far end of the right side. How can I make this at the center as well?

enter image description here

Codesandbox: https://codesandbox.io/s/xenodochial-fog-s984v0?file=/src/App.js

codes:

 const options = {
    filter: true,
    selectableRows: "none",
    responsive: "simple",
    expandableRows: true,
    renderExpandableRow: (rowData, rowMeta) => {
      console.log(rowData, "rowData");
      return Object.entries(rowData[3]).map(([key, value]) => {
        return (
          <TableContainer>
            <Table>
              <TableHead>
                <TableCell align="right">Name</TableCell>
                <TableCell align="right">Color</TableCell>
              </TableHead>
              <TableBody>
                <TableRow key={key}>
                  <TableCell component="th" scope="row">
                    {value.name}
                  </TableCell>

                  <TableCell align="right">{value.color}</TableCell>

                  {/* Product: {value.name} + {value.size} +{" "}
                  {value.color + value.quantity} */}
                </TableRow>
              </TableBody>
            </Table>
          </TableContainer>
        );
      });
    }
  };

Solution

  • Changing your options object like below, shoud resolve issue.

    const options = {
        filter: true,
        selectableRows: "none",
        responsive: "scrollMaxHeight",
        expandableRows: true,
        renderExpandableRow: (rowData, rowMeta) => {
          console.log(rowData);
          return (
            <tr>
              <td colSpan={4}>
                <TableContainer>
                  <Table style={{ margin: "0 auto" }}>
                    <TableHead>
                      <TableCell align="right">Name</TableCell>
                      <TableCell align="right">Color</TableCell>
                    </TableHead>
                    <TableBody>
                      {rowData[3].map((row) => {
                        console.log(row);
                        return (
                          <TableRow key={row.id}>
                            <TableCell component="th" scope="row" align="right">
                              {row.name}
                            </TableCell>
                            <TableCell align="right">{row.color}</TableCell>
                          </TableRow>
                        );
                      })}
                    </TableBody>
                  </Table>
                </TableContainer>
              </td>
            </tr>
          );
        }
      };