Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.js - HTML Table nested rows are not correctly rendered

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:

Table Prreview

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>
  );
}
like image 760
Ven Nilson Avatar asked Sep 12 '26 09:09

Ven Nilson


1 Answers

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

enter image description here

like image 105
ranquild Avatar answered Sep 14 '26 00:09

ranquild