0

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.)

1
  • "Why is that" - because .forEach does not do what you think it does. You want .map instead. Commented Oct 11, 2022 at 3:29

1 Answer 1

2

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>
))}
Sign up to request clarification or add additional context in comments.

2 Comments

I'm not a React user, so forgive my ignorance - but I assume that key="" attribute values have to be unique in their context, right? So what happens if duplicate heading values end-up being used here?
It could produce some potential bugs when you add/remove elements from theadData. A common workaround is to also associate indexes to the key, such as .map((heading, index) => <tr key={heading + index}>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.