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.