sowmyasree sowmyasree - 2 months ago 31
React JSX Question

How to map inside a map function in reactjs

I have my table view.And i have posfields that are perfecting displaying by
using map function.But my problem is when i'm trying to map td inside posfields map function its throwing me the error "'headers' of undefined".

{
this.POSFields.map(function (posFields, POSFieldsId) {
return (
<tr>
<td className="posheader" key={POSFieldsId} value={posFields.POSFieldsId}
{posFields.POSFields} </td>
<td>
<select className="selectpicker">
<option value="">Select Value</option>
{this.headers.map(function (headers) {
return (
<option key={headers}>{headers}</option>
);
})}
</select>
</td>
</tr>
)
})
}

Answer Source

Like @Andrew already suggested, you should use arrowfunctions in order to be able to access this within your map. You currently loose the context of this

{
  this.POSFields.map((posFields, POSFieldsId) => {
    return (
      <tr>
        <td className="posheader" key={POSFieldsId} value={posFields.POSFieldsId}
          {posFields.POSFields} </td>
    <td>
          <select className="selectpicker">
            <option value="">Select Value</option>
            {this.headers.map((headers) => {
              return (
                <option key={headers}>{headers}</option>
              );
            })}
          </select>
        </td>
      </tr>
    )
  })
}