Maria Jane Maria Jane - 2 months ago 5
React JSX Question

i is not defined using map() with ES6

Trying to create a li in react but failed. Error is near the map(), I got error of i is not defined, why?

const TodoItems = React.creatClass({
getInitialState() {
return {
items : [
{id:1,name:"Gym"},
{id:2,name:"Jump"},
{id:3,name:"Racing"}
]
}
},
renderItem(){
return(
<ul>
this.state.items.map(item,i =>
<li key={i}>item.name</li>
)
</ul>
)
},
render(){
return (
<renderItem />
)
}
})

Answer

When you have multiple arguments for an arrow function, you need to put () around them. So:

this.state.items.map((item,i) => 
// ------------------^------^
    <li key={i}>item.name</li>
)

Your original code calls map with item as its first argument, and an arrow function taking a single argument (i) as its second argument.

You also need to put item.name in {} and put the call to map in {}:

renderItem(){
  return(
    <ul>
    {this.state.items.map((item,i) => 
      <li key={i}>{item.name}</li>
    )}
    </ul>
  ) 

Then it works:

const { Component } = React;
const { render } = ReactDOM;

const TodoItems = React.createClass({
  getInitialState() {
    return {
      items : [
        {id:1,name:"Gym"},
        {id:2,name:"Jump"},
        {id:3,name:"Racing"}
      ] 
    }
  },
  renderItem(){
    return(
      <ul>
      {this.state.items.map((item,i) => 
        <li key={i}>{item.name}</li>
      )}
      </ul>
    ) 
  },
  render(){
    return this.renderItem();
  }
});
    
render(<TodoItems /> , document.getElementById('items'));
<div id="items"></div>
<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>

That became clear to me when I used Babel's REPL to compile the JSX and realized I was seeing "this.state.map((item,i) =>" as a string.

Comments