I'm facing an issue with rendering the table data. There are a total of four columns and the last two columns can also contain nested rows. But facing a problem rendering this behavior How can I achieve this via the HTML table element in React.js?
Please see the screenshot as an example:

Code:
const data = [
{
product: "Shirt",
price: "$20",
attributes: [
{ type: "Color", value: "Red" },
{ type: "Color", value: "" },
{ type: "Color", value: "Brown" },
],
},
{
product: "Shirt 2",
price: "$25",
attributes: [
{ type: "Color", value: "Red" },
{ type: "", value: "Yellow" },
{ type: "Color", value: "Brown" },
],
},
{
product: "Shirt 3",
price: "$20",
attributes: [{ type: "Color", value: "Red" }],
},
{
product: "Shirt 4",
price: "$30",
attributes: [],
},
];
export default function TableComponent() {
return (
<Fragment>
<div>
<table>
<thead>
<tr>
<th>Product</th>
<th>Price</th>
<th>Attributes</th>
<th>Values</th>
</tr>
</thead>
<tbody>
{data.map((ele, index) => {
return (
<tr key={`row-${index}`}>
<td>{ele.product}</td>
<td>{ele.price}</td>
{ele.attributes.map((attr, index) => {
return (
<Fragment key={`attr-${index}`}>
<td>{attr.type}</td>
<td>{attr.value}</td>
</Fragment>
);
})}
</tr>
);
})}
</tbody>
</table>
</div>
</Fragment>
);
}
You can use the rowspan attribute on the td element. It makes the cell span across multiple table rows. For you case you need to add td with rowspan in the first row for each "product", and other rows for this product would have first 2 td elements omitted. A working example https://codesandbox.io/s/frosty-mendeleev-p8cwx3?file=/src/App.js

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