Ben Walker Ben Walker - 9 months ago 100
React JSX Question

react dynamic table rows

I have a react table that's mapping over an array of objects. I want to also map over one of the properties of those objects to create more rows. The object property I want to map over is also an array of objects. So my data look something like this:

[
{id:1,name:"fakeName",children:[{id:10,name:"fakeChildName"}]},
{id:2,name:"fakeName2",children:[{id:11,name:"fakeChildName11"}]}
]


Then, in my
render()
, I have this inside a table:

<tbody>
{myArray.map(row => (
<tr key={`row-${row.name}`}>
<td>
<div className="parent">{row.id}</div>
</td>
<td>{row.name}</td>
<td />
<td />
<td />
</tr>
))}
</tbody>


This renders just fine. I want to iterate over the row.children objects to create more rows to fill up columns 3, 4, and 5 of that same table body. So I did this:

<tbody>
{myArray.map(row => (
<tr key={`row-${row.name}`}>
<td>
<div className="parent">{row.id}</div>
</td>
<td>{row.name}</td>
<td />
<td />
<td />
</tr>
{row.children.map(childRow => (
<tr key={`row-child-${childRow.name}`}>
<td />
<td />
<td>{childRow.id}</td>
<td>{childRow.name}</td>
<td><button>myButton</button></td>
</tr>
))}
))}
</tbody>


When I add that piece, I get an unexpected token error on the line where I have my
{row.children.map...
saying it's expecting a comma there. I'm not sure how to do this properly.

Exo Exo
Answer Source

You are closing the <tr> on the line before {row.children.map... which is illegal JSX. You can instead return an array of JSX:

{myArray.map(row => ([
  <tr key={`row-${row.name}`}>
    <td>
      <div className="parent">{row.id}</div>
    </td>
    <td>{row.name}</td>
    <td />
    <td />
    <td />
  </tr>,
  {...row.children.map(childRow => (
    <tr key={`row-child-${childRow.name}`}>
      <td />
      <td />
      <td>{childRow.id}</td>
      <td>{childRow.name}</td>
      <td><button>myButton</button></td>
    </tr>
  ))}
]))}

You can tell this makes things nasty, so I'd prefer clarity over brevity here:

{myArray.map(row => {
  const parentRow = (
    <tr key={`row-${row.name}`}>
      <td>
        <div className="parent">{row.id}</div>
      </td>
      <td>{row.name}</td>
      <td />
      <td />
      <td />
    </tr>
  );
  const childrenRows = row.children.map(childRow => (
    <tr key={`row-child-${childRow.name}`}>
      <td />
      <td />
      <td>{childRow.id}</td>
      <td>{childRow.name}</td>
      <td><button>myButton</button></td>
    </tr>
  ));

  return [parentRow, ...childrenRows];
})}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download