Expand/Collapse TableRow component in Material-UI
Asked Answered
V

4

17

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 ?

Vincentia answered 12/6, 2016 at 11:6 Comment(1)
You can use github.com/gregnb/mui-datatablesBolanger
F
10

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.

Flowering answered 9/5, 2020 at 17:17 Comment(0)
S
5

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
Spondee answered 6/3, 2019 at 10:35 Comment(2)
Are there solution to avoid divs within <tr>? <tr><div><td/></div> ?Echinoderm
This suggestion still throws the warning Warning: validateDOMNesting(...): <td> cannot appear as a child of <div>Countershaft
C
4

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>
    </>
  )
}
Countershaft answered 1/4, 2020 at 2:34 Comment(0)
V
2

<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

Vincentia answered 31/3, 2019 at 11:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.