Arun Arun - 1 month ago 7
Javascript Question

react ES5 style function call back doesn't work

I am trying to pass a ES5 style callback to the map function of the array. It doesn't work, but when i change it to an arrow function everything goes well

render(){
return (
<ul>
{this.props.items.map((item, index) => (
<li key={index}>{item}</li>
))
}
</ul>
);
}


The following code doesn't work

return (
<ul>
{this.props.items.map(function(index, item) { (
<li key={index}>{item}</li>
)})
}
</ul>
);


I have tried function(item, index) as well. Does not work. There is no error. Function is not executed and no li element is rendered

Answer

You need to include a return statement, which included by default in ES6

return  (
        <ul>
        {this.props.items.map(function(index, item) { return (
                <li key={index}>{item}</li>
        );})
        }
        </ul>
    );
Comments