Eslint Error - Unexpected block statement surrounding arrow body; move the returned value immediately after the =>
If you use arrow functions you have two syntax options when returning values:
- () => { return somethinng }
- () => expression
In the second case you just write expression that is automatically returned. The eslint rule that is giving you the error is telling you that if you have just one expression you can remove the curly braces and return the expression directly like this:
{
this.state.items.map((item) => (
<div key={item}>
<a href={item.mainContact.phoneHref + item.mainContact.phone}>
<i className="fa fa-phone" />
<strong>{item.mainContact.phone}</strong>
</a>
</div>
)
);
}
you're using airbnb eslint preset
that enforces that arrow functions do not use braces if you just return one object.
Change your code to this and it should compile
this.state.items.map((item) => (<div key={item}>
<a href={item.mainContact.phoneHref + item.mainContact.phone}>
<i className="fa fa-phone" />
<strong>{item.mainContact.phone}</strong>
</a>
</div>)
)
See docs for that rule
See where is configured in the airbnb repo
Simply remove your return() function and put whole block into function like this
{
this.state.items.map((item) => (
<div key={item}>DATA</div>
)
}
Here is examples how it work:
() => { return <div key={item}>DATA</div>}
so after remove our return function it will work like that
() => (<div key={item}>DATA</div>)
or
() => yourState
The rule is saying that you can remove the curly braces along with the "return" surrounding the that you're returning. However, returning a if statement would require the curly braces.
This is the correct solution to your question based on the lint error:
{
this.state.items.map((item) => (
<div key={item}>
<a href={item.mainContact.phoneHref + item.mainContact.phone}>
<i className="fa fa-phone" />
<strong>{item.mainContact.phone}</strong>
</a>
</div>
)
);
}
The curly braces would however be needed if you were returning multiple expressions. Here's a example using a if statement:
{
this.state.items.map((item) => {
if (!item.mainContact.phone) {
return (
<div key={item}>
<span>n/a</span>
</div>
)
}
return (
<div key={item}>
<a href={item.mainContact.phoneHref + item.mainContact.phone}>
<i className="fa fa-phone" />
<strong>{item.mainContact.phone}</strong>
</a>
</div>
);
})
}
Add the below code :
"arrow-body-style": "off"