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:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With