AtomicCommit
AtomicCommit

Reputation: 39

React JS: How to map component table row correctly?

So I've created this Table component, intended to be reusable.

But I have this problem where the data didn't fill all the row correctly. It stacked up on first two rows.

Here's my code so far:

Menu.js

export const AddMenu = () => {
  const theadData = ["No", "Name", "Category", "Price"];
  const tbodyData = [
    {
      id: 1,
      items: [1, "Hamburger", "Fast Food", 150],
    },
    {
      id: 2,
      items: [2, "Pizza", "Fast Food", 100],
    },
  ];

  return (
    <div className="container">
      <h1>Add Menu</h1>
      <Table theadData={theadData} tbodyData={tbodyData} />
    </div>
  );
};

Table.js

export const Table = ({
  theadData,
  tbodyData,
}) => {
  return (
    <div className="table">
      <table>
        <thead>
          <tr>
            {theadData.map((item) => {
              return <th title={item}>{item}</th>;
            })}
          </tr>
        </thead>
          <tr>
            {tbodyData.map((item) => {
              return <td key={item}>{item.items}</td>;
            })}
          </tr>
        </tbody>
      </table>
    </div>
  );
};

Thanks btw, hope to get an answer.

Upvotes: 0

Views: 1790

Answers (1)

Mr. Hedgehog
Mr. Hedgehog

Reputation: 2885

Add second map to loop over rows, and then loop over cells, like this:

{
  tbodyData.map((row, index) => (
    <tr key={index}>
      {row.map((item) => {
        return <td key={item}>{item}</td>;
      })}
    </tr>
  ));
}

Upvotes: 2

Related Questions