JCrew0
JCrew0

Reputation: 129

How do I dynamically generate table rows without jquery?

Currently, I have a table class as follows:

import React from "react";
import "./Table.css";

export default function Table({theadData, tbodyData}) {
  return (
    <>
      <table>
        <tr>
          <th></th>
          <th>2017</th>
        </tr>
        {Array.from(theadData).forEach(heading => {
            <tr>
              <td class="largeHeader" key={heading}>{heading}</td>
              <td class="primaryCell">{tbodyData[heading].value}</td>
            </tr>;
        })}
      </table>
    </>
  );
}

When I add console.log(heading) or console.log(tbodyData[heading].value) within the loop, I can see that they give the expected values. However, none of the rows are added on. Why is that and how can I solve this problem? (I'd prefer to avoid jquery and libraries of that nature if possible, but am open to ideas.)

Upvotes: 0

Views: 51

Answers (1)

Hao Wu
Hao Wu

Reputation: 20669

There are several mistakes you made:

  1. change forEach to map
  2. replace {} with (), or add return before <tr>
  3. put key on the root element which is <tr>
{Array.from(theadData).map(heading => (
   <tr key={heading}>
     <td className="largeHeader">{heading}</td>
     <td className="primaryCell">{tbodyData[heading].value}</td>
   </tr>
))}

Upvotes: 2

Related Questions