Jessie Campbell Jessie Campbell - 2 months ago 13
Javascript Question

react map es6 arrow function doesn't work

I have below code and it render nothing, I wonder where is my mistake, I did not see any error in the console.

var App = React.createClass({
getInitialState(){
return {
items:[1,2,3]
}
},
renderItem(){
this.state.items.map((item,i)=> <li key={i}>{item}</li>)
},
render(){
return(
<ul>
{this.renderItem}
</ul>
)
}
})

React.render(<App />, document.getElementById('container'));


http://jsfiddle.net/3Ley7uac/

Need advise.

Answer

First of all you need to call your method with ():

  <ul>
    {this.renderItem()}
  </ul>

Secondly you ned to return inside the method:

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

These are just vanilla Javascript class methods. There's nothing special React does here. You need to call methods and return values the same way you would with any Javascript code.