Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expand/Collapse TableRow component in Material-UI

I need to expand the TableRow component to open another div containing some fields. But React throws a warning if I try to add divs in the table body.

warning: validateDOMNesting(...): <div> cannot appear as a child of <tr>. See RowComponent > TableRow > tr > div.

Required functionality is similar to ^ button from the nested list component to collapse / expand. Is there any way to customize the material-ui TableRow to expand/collapse ?

like image 309
knewsense Avatar asked Jun 12 '16 11:06

knewsense


4 Answers

The material-ui site table component page has an example of a "Collapsible table": https://material-ui.com/components/tables/#collapsible-table.

That example is exactly what I was looking for, and I'm sure many others as well.

like image 53
Chris Avatar answered Nov 09 '22 23:11

Chris


This solution works, you can also add colSpan to the TableCell that contains the Collapse to match the border width with the number of TableCells at the top.

function ExpandingRow({ summary, details }) {
  const [open, setOpen] = React.useState(false)

  return (
    <>
      <TableRow hover onClick={() => { setOpen(!open) }}>
        <TableCell>
          {summary}
        </TableCell>
      </TableRow>

      <TableRow>
        <TableCell style={{ padding: 0 }}>
          <Collapse in={open}>{details}</Collapse>
        </TableCell>
      </TableRow>
    </>
  )
}
like image 34
Raul Madrigal Avatar answered Nov 10 '22 00:11

Raul Madrigal


Depending on your use-case you may want to use expansion panels instead.

If you still want to use a table, you can set the component prop on the Collapse component. You'll have to use this outside of your original TableRow. Inside of a TableCell or td, you can use any element you want. Check out this codesandbox for a working example.

The interesting snippet:

<Collapse in={open} component="tr" style={{ display: "block" }}>
  <td>
    <div>Expanded data.</div>
  </td>
</Collapse>

The important parts here:

  1. component="tr" tells the Collapse component to use a tr instead of a div
  2. display: "block" to overwrite the default display: "table-row" of the tr component
like image 36
Lorenz Henk Avatar answered Nov 10 '22 00:11

Lorenz Henk


<div> is not supported inside a TableRow. Removing the <div> tag and using a Card component in its place worked for me.

You can see the code here : https://github.com/shiveeg1/tracker-quick-entry/blob/master/src/components/super-row.js

Also there are multiple alternatives provided on this thread which were very helpful: https://github.com/mui-org/material-ui/issues/4476

like image 2
knewsense Avatar answered Nov 10 '22 00:11

knewsense