Skip to content Skip to sidebar Skip to footer

Map Is Not A Function In Jsx

This block of code caused error of map is not a function {data && (data.devices || {}).map((obj, i) =>
{obj.name}
)} I just don't get it,

Solution 1:

There is no native .map to {}, so replace data.devices || {} to data.devices || []

{(data && data.devices || []).map((obj, i) => 
    <div>{obj.name}</div>
)}

Solution 2:

In this case map is not a function because when data.devices is empty, the default value is an empty object hence map is not a function of an object. Take this for example:

// simulate scenarios
const data00 = undefined;
const data01 = {};
const data02 = { devices: null };
const data03 = { devices: [] };
const data04 = { devices: [{ name: 'device01' }, { name: 'device02' }] }


class Main extends React.Component {
  render() {
    return (
      <div>
        {this.load(data00)}
        {this.load(data01)}
        {this.load(data02)}
        {this.load(data03)}
        {this.load(data04)}
      </div>
    );
  }
  
  /**
   * Loads data and renders the devices if there's any
   */
  load(data) {
    return (!!data && data.devices || []).map((obj, i) => 
       <div key={i}>{obj.name}</div>
    );
  }
}

ReactDOM.render(<Main />, document.getElementById('main'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="main"/>

As you can see, only data04's devices will be rendered.


Post a Comment for "Map Is Not A Function In Jsx"