I'm trying to create a table React component that will take in data and headings as props. I've run into a problem where I can't get the forEach
method of Map won't create the necessary children elements.
The input prop for columns looks like this:
let cols = {
payment: 'Payment',
date: 'Processing Date',
amount: 'Amount',
payee: 'Payee'
};
Here's a method of my React table component that generates the heading elements:
generateTableHead() {
let columnsMap = new Map((Object.entries(this.props.columns)));
let i = 0;
return (
<tr>
{columnsMap.forEach((columnValue) =>
<th key={i++}>
{columnValue}
</th>
)}
</tr>
);
}
The problem is that the <th>
children don't exist in the <tr>
object that's returned; I get an emtpy <tr></tr>
.
However, if I use Array.prototype.map, the children <th>
elements WILl be created properly.
generateTableHead() {
let columnsArray = Object.entries(this.props.columns);
return (
<tr>
{columnsArray.map((column, index) =>
<th key={index}>{column[1]}</th>
)}
</tr>
);
}
I prefer the first version because the code is slightly more understanding since I'm going to reference keys and values in the Map object, rather than using array indices in the second version.
I'm sure there is a very simple explanation for this, or I've made a very simple error that I just can't spot. If anyone can point out the problem, I'd greatly appreciate it!