Reputation: 1894
All the docs for map
use braces but the code below and most examples I see when dealing with React use parenthesis. I'm trying to figure out exactly what the difference is and what the code is doing.
When using braces, nothing renders unless I specifically add return
. So my take is that the parenthesis act as some sort of inline function that automatically returns or React converts the result and inlines it into the JSX?
// Renders fine
render()
{
return (
<div className="item-list">
{
this.props.items.map(
( _item, _index ) => (
<ItemComponent
key={ _index }
name={ _item.name }
description={ _item.description }
/>
) )
}
</div>
);
}
// Nothing
render()
{
return (
<div className="item-list">
{
this.props.items.map(
( _item, _index ) =>
{
<ItemComponent
key={ _index }
name={ _item.name }
description={ _item.description }
/>
} )
}
</div>
);
}
// Renders fine
render()
{
return (
<div className="item-list">
{
this.props.items.map(
( _item, _index ) =>
{
return <ItemComponent
key={ _index }
name={ _item.name }
description={ _item.description }
/>
} )
}
</div>
);
}
Upvotes: 0
Views: 6492
Reputation: 799
So parenthesis in an arrow function returns a single value, the curly braces are used when executing multiple lines of code and not just a simple return, so a manual return statement is required just because javascript can't know what among those lines to return.
materials.map(material => ({key:material.name}));
return an object
materials.map(material => {
let newMat = material.name+'_new';
return newMat;
});
we need to return since we are doing 1 or many lines of manipulation and trying to return end result
Upvotes: 0
Reputation: 36117
Nothing to do with React, It is all about javascript
Curly braces saying it is a function body so we need to manually use return
keyword
this.props.items.map(
( _item, _index ) =>
{ // Note: represent function body, normal javascript function
<ItemComponent
key={ _index }
name={ _item.name }
description={ _item.description }
/>
} )
According to arrow functions
, has implicit return behavior hence so need to mention explicitly if single line expression.
render()
{
return (
<div className="item-list">
{
this.props.items.map(
( _item, _index ) => ( // Note: single line expression, so impilicit;y return our ItemComponent
<ItemComponent
key={ _index }
name={ _item.name }
description={ _item.description }
/>
) )
}
</div>
);
}
Upvotes: 1