Whitecat
Whitecat

Reputation: 4020

Create a 2 column table from an array in JSX

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

Answers (2)

Arpit Agrawal
Arpit Agrawal

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 :

Edit react-konva-basic-demo

Upvotes: 1

Marcus
Marcus

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

Related Questions