I'm new to React and now I'm taking a course on Pluralsight.
Let's take this example:
const Card = (props) => {
var profile = props;
return (<div className="github-profile">
<img src={profile.avatar_url} />
<div className="info">
<div className="name">{profile.name}</div>
<div className="company">{profile.company}</div>
</div>
</div>);
};
This is a function component but this can be rewrite like:
const Card = (props) => (
<div className="github-profile">
<img src={props.avatar_url} />
<div className="info">
<div className="name">{props.name}</div>
<div className="company">{props.company}</div>
</div>
</div>
);
What is the actual difference? Aren't the same thing? When you use () and when {}?
An arrow function can have one of two forms:
(args) => { /* statements */ }
(args) => returnValue
as a shorthand for (args) => { return returnValue }
The (args) => (...)
form that you mentioned is actually just form #2 with extra parentheses (which may be necessary if returning an object literal for example, because otherwise it would be ambiguous with form #1, and they are standard for returning a JSX expression like <Thing>...</Thing>
).
If you want to do more than just return
ing something, you'll use form #1. Otherwise form #2 will suffice.
(Note: If there is exactly one argument, the left-hand parentheses are optional - args => ...
is the same as (args) => ...
)