5

I have the array like this :

const sample = [
  { name: 'apple', detail: [{'a', 'b'}]},
  { name: 'banana', detail: [{'a', 'b'}]},
];

Let's say I want to create a table looks like the following attachment:

enter image description here

That's the table body part, and I have put all the details in inside of . It's creating the table as I expected but the size is really narrow and also doesn't match with the table head.

I was wondering if there's a smart way to have map multiple data in a row and embed in one table cell.

The name part (which are apple and banana) must be the first table cell with row span.

1 Answer 1

8

You can do that using rowSpan on your TableCell. Just assign it a value of detail.length + 1

Here, give this a try:

import React, { Fragment } from "react";
import { makeStyles } from "@material-ui/core/styles";
import Table from "@material-ui/core/Table";
import TableBody from "@material-ui/core/TableBody";
import TableCell from "@material-ui/core/TableCell";
import TableHead from "@material-ui/core/TableHead";
import TableRow from "@material-ui/core/TableRow";
import Paper from "@material-ui/core/Paper";

const useStyles = makeStyles(theme => ({
  root: {
    width: "100%",
    marginTop: theme.spacing(3),
    overflowX: "auto"
  },
  table: {
    minWidth: 700
  }
}));

const sample = [
  { name: "apple", detail: ["a", "b", "c", "d"] },
  { name: "banana", detail: ["a", "b"] }
];

export default function SpanningTable() {
  const classes = useStyles();

  return (
    <Paper className={classes.root}>
      <Table className={classes.table}>
        <TableHead>
          <TableRow>
            <TableCell>Fruit</TableCell>
            <TableCell align="right">Buyers</TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {sample.map(item => (
            <Fragment>
              <TableRow>
                <TableCell rowSpan={item.detail.length + 1}>
                  {item.name}
                </TableCell>
              </TableRow>
              {item.detail.map(detail => (
                <TableRow>
                  <TableCell>{detail}</TableCell>
                </TableRow>
              ))}
            </Fragment>
          ))}
        </TableBody>
      </Table>
    </Paper>
  );
}

Here's a Working Sample CodeSandbox Demo for your ref.

Sign up to request clarification or add additional context in comments.

1 Comment

This has a problem if there are w few rows that has only one item and not many... a blank space is shown

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.