Categories
React Answers

How do to Wrap a React Component that Returns Multiple Table Rows and Avoid the “tr cannot appear as a child of div” Error?

Spread the love

Sometimes, we may see the “<tr> cannot appear as a child of <div>” error in React when we wrap a div around a table row.

In this article, we’ll look at how to fix the “<tr> cannot appear as a child of <div>” error in React.

Fix the “<tr> Cannot Appear as a Child of <div>” Error

To fix the “<tr> cannot appear as a child of <div>” error in React, we should remove the wrapper div.

For instance, we can write:

import React from "react";

const data = [
  { firstName: "jane", lastName: "smith" },
  { firstName: "john", lastName: "doe" },
  { firstName: "may", lastName: "wong" }
];

const Rows = data.map((d) => {
  return (
    <tr key={d.firstName}>
      <td>{d.firstName}</td>
      <td>{d.lastName}</td>
    </tr>
  );
});

export default function App() {
  return (
    <table>
      <thead>
        <tr>
          <th>first name</th>
          <th>last name</th>
        </tr>
      </thead>
      <tbody>{Rows}</tbody>
    </table>
  );
}

to create the Rows array, which has the JSX for the tr elements that we created by mapping them from the data array with map .

Then we pass that straight into the tbody to render the array of table rows.

Conclusion

To fix the “<tr> cannot appear as a child of <div>” error in React, we should remove the wrapper div.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *