A worthy programmer
A worthy programmer

Reputation: 15

Is it possible to add "Sub-Headers/Columns" to a Material Table Table in React?

I am creating a table for larger more complex data sets using react and the material-table library. Is there a way to add sub-header/columns to the material-table? So: title title1 | title2

Upvotes: 1

Views: 5540

Answers (2)

Shakya Karunathilake
Shakya Karunathilake

Reputation: 535

I had the same problem few months ago. I only could achieve what I wanted by overriding the Header component of the material-table.

components={{ Header: props => (
<TableHead {...props}>
  <TableRow>
    <TableCell rowSpan={2}> Column 1 </TableCell>
    <TableCell colSpan={2}> Column 2 </TableCell>
    <TableCell colSpan={2}> Column 3 </TableCell>
    <TableCell rowSpan={2}> Column 4 </TableCell>
    <TableCell rowSpan={2}> Action </TableCell>
  </TableRow>
  <TableRow>
    <TableCell> Column 2 A </TableCell>
    <TableCell> Column 2 B </TableCell>
    <TableCell> Column 3 A </TableCell>
    <TableCell> Column 3 B </TableCell>
  </TableRow>
</TableHead>
), }}

If you are using the editable material-table u should have a tablecell called Action. And when you are inserting the columns it should be as usual. For example:

columns = {
  [{
      field: "column1",
      title: "Column 1"
    },
    {
      field: "column2a",
      title: "Column 2 A"
    },
    {
      field: "column2b",
      title: "Column 2 B"
    },
    {
      field: "column3a",
      title: "Column 3 A"
    },
    {
      field: "column3b",
      title: "Column 3 B"
    },
    {
      field: "column4",
      title: "Column 4"
    },
  ]
}

You will have to style it using inline css and/or makeStyles (material ui) to make it look presentable. Hope this helps. Please feel free to ask if you need more explainations.

Upvotes: 1

Mile Mijatović
Mile Mijatović

Reputation: 3177

Try with Column Grouping

You can group column headers by rendering multiple table rows inside a table head:

<TableHead>
  <TableRow />
  <TableRow />
</TableHead>

Upvotes: 0

Related Questions