Grid Layout mapped array - react

Viewed 12

Im mapping an array and want to display each prop of mapped item under its column category - name below Item Name, quantity below QTY., etc. Now im getting each item displayed below following columns - first whole item below Item Name, etc. Its obviously expected behaviour but how to properly display each prop under its column category?

import { ReactElement } from "react";
import styled from "styled-components";
import { Invoice } from "../../../Root/Root.utils";

type Props = {
  invoice?: Invoice;
};

export const SummaryPart = ({ invoice }: Props): ReactElement => {
  return (
    <Summary>
      <Items>
        <p>Item Name</p>
        <p>QTY.</p>
        <p>Price</p>
        <p>Total</p>
        {invoice?.items.map((item) => (
          <Item>
            <h3>{item.name}</h3>
            <span>{item.quantity}</span>
            <span>{item.price}</span>
            <span>{item.total}</span>
          </Item>
        ))}
      </Items>
    </Summary>
  );
};

const Summary = styled.div`
  width: 100%;
  border-radius: 8px;
  background-color: rgba(249, 250, 254, 1);
  padding: 2rem;
`;

const Items = styled.div`
  display: grid;
  grid-template-columns: repeat(4, 1fr);
`;

const Item = styled.div``;
1 Answers

I would recommend using a table

<table>
  <thead>
    <tr>
      <th>Item Name</th>
      <th>QTY.</th>
      <th>Price</th>
      <th>Total</th>
    </tr>
  </thead>
  <tbody>
    {invoice?.items.map((item) => (
      <tr>
        <td>{item.name}</td>
        <td>{item.quantity}</td>
        <td>{item.price}</td>
        <td>{item.total}</td>
      </tr>
    ))}
  </tbody>
</table>

If you really want to use the grid layout, you can add the following to Items:

grid-template-rows: repeat(${invoice.length}, 1fr);
Related