Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map inside a map function in reactjs

Tags:

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>
    )
  })
}
like image 878
sowmyasree Avatar asked Aug 28 '17 07:08

sowmyasree


People also ask

How do you map data in React JS?

In React, the map method is used to traverse and display a list of similar objects of a component. A map is not a feature of React. Instead, it is the standard JavaScript function that could be called on an array. The map() method creates a new array by calling a provided function on every element in the calling array.


2 Answers

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>
    )
  })
}
like image 154
Nocebo Avatar answered Oct 05 '22 02:10

Nocebo


Bind map function to have access to this context:

{
  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>
    )
  }.bind(this))
}

Or the arrow functions this.POSFields.map((posFields, POSFieldsId) => {

like image 30
Andrew Avatar answered Oct 05 '22 03:10

Andrew