Fairly new to React with a potential silly question.
How is it possible that I can omit Reacts return statement with parenthesis.
const Nav = () => (
<nav className="c_navbar">
{ some jsx magic here }
</nav>
)
while I see other instances like this:
const Nav = () => {
return (
<nav className="c_navbar">
{ some jsx magic here }
</nav>
)
}
As far as I understand the ()
help when I return an object literal so that it doesn't mix it up with a code block. But I don't see this applicable here?
Thanks
The first snippet is implicit return. Parentheses are provided only for developer's convenience; it's possible to unambiguously parse the code without them, at the expense of readability:
const Nav = () =>
<nav className="c_navbar">
{ some jsx magic here }
</nav>
While the second snippet contains explicit return. This is the case when parentheses are commonly used in React, because when there's no optional expression right after return
statement, there is no returned value.
return
<nav className="c_navbar">
{ some jsx magic here }
</nav>
is parsed as
return;
<nav className="c_navbar">
{ some jsx magic here }
</nav>
In order to be parsed correctly without parentheses, it should be:
return <nav className="c_navbar">
{ some jsx magic here }
</nav>
So parentheses are commonly used for consistency in both implicit and explicit returns and allow to improve the readability with proper indentation.
This is a JavaScript question not a React Question.
1) Parenthesis () are used in an arrow function to return an object.
() => ({ name: 'Amanda' }) // Shorthand to return an object
That is equivalent to
() => { // Block body
return { name : 'Amanda' }
}
class StarsComponent {
constructor(size) {
this.size = size;
}
render() {
return (<div>
*
</div>) // <--JavaScript engine inserts semicolon here
}
}
Why? When you place your opening bracket on the same line as return: return ( You are telling JavaScript engine that it can’t automatically insert a semicolon until the bracket is closed.
For a single line statement, we don’t need to wrap it inside brackets.
class StarsComponent {
constructor(size) {
this.size = size;
}
// Not required to wrap brackets around a single line of code
render() {
return <div>*</div>;
}
}
More information can be found here: https://medium.com/@leannezhang/curly-braces-versus-parenthesis-in-reactjs-4d3ffd33128f
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With