Reputation: 4020
I am trying to generate 2 columns in each row of a table from an array in JSX. In Javascript it would be simple but JSX needs the opening and closing tag in the same area.
This is what I would do in Javascript:
var tTable = '<table>';
var newArray = ['2', '3', '4', '5', '6'];
var newTr = '';
for (var i = 0; i < newArray.length; i++) {
if (i % 2 == 0) {
newTr += (i > 0) ? '</tr><tr>' : '<tr>'
}
newTr += '<td>' + newArray[i] + '</td>';
}
newTr += '</tr>';
tTable += newTr + '</table>';
document.write(tTable);
This will produce an array as follows:
2 3
4 5
6
Upvotes: 0
Views: 2296
Reputation: 1180
This should help :
showTable() {
const tableRows = [];
for (let i = 0; i < newArray.length; i = i + 2) {
tableRows.push(
<tr key={newArray[i] + "-" + newArray[i + 1] + "-" + i}>
<td style={{ border: "1px solid black " }}>
{newArray[i]}
</td>
<td style={{ border: "1px solid black " }}>
{newArray[i + 1]}
</td>
</tr>
);
}
return tableRows;
}
render() {
return (
<table style={{ border: "1px solid black " }}>
<tbody>
<th style={{ border: "1px solid black " }}>column1</th>
<th style={{ border: "1px solid black " }}>column2</th>
</tbody>
<tbody>{this.showTable()}</tbody>
</table>
);
}
}
Working solution :
Upvotes: 1
Reputation: 2321
You could try the following:
render() {
return
<table>
<tbody>
{
newArray.map((entry, index) => {
if (index === newArray.length - 1) {
return <tr><td>entry</td></tr>
}
return (
<tr>entry</tr>
<tr/>
)
})
}
</tbody>
</table>
)
}
I know React complains if you dont nest your <tr>
s in a <tbody>
. Hopefully that should give you what you want. The translation to a functional component case should be trivial.
Hope that helps.
Upvotes: 0