Reputation: 1375
What is the difference between the two and which one is better?
const Person=({firstName,lastName})=>{
return(
<div>
<p>{'${firstName}${lastName}'}</p>
</div>
)
}
or
const Person=(props)=>{
return(
<div>
<p>{props.firstName}{props.lastName}</p>
</div>
)
}
Upvotes: 0
Views: 90
Reputation: 129
There is no good or bad. Actually, it depends on you. But I would recommend that you use destruction to get access to your object's properties. Because it's clean and easy to understand there's no clutter and no need to repeatedly access props.
Upvotes: 1
Reputation: 133
I will give you a example when I use first method:
class Person({firstName, lastName, ...props)} => {
return (
<>
<p>{firstName}</p>
<p>{lastName} </p>
<ChildComponent {...props} />
</>
)
}
Instead writing all props
to <ChildComponent/>
i use {...props}
. Or my ChildComponent
doesn't have a fixed number of props etc. I mostly use that when I make reusable components.
Upvotes: 2
Reputation: 8316
Actually the first one should be :-
const Person=({firstName,lastName})=>{
return(
<div>
<p>{'${firstName}${lastName}'}</p>
</div>
)
}
You need to destructure the properties from the props
object which React makes for you.
There is no one good or bad here. Both can serve your purpose. Use the second one where writing props.blabla
becomes a headache for you and where the blabla
alone makes more sense to use.
Edit - @xflorin94 added a good example where you only extract the required properties from the props
object that are relevant for current component usage and you can use ...
to get the rest of the properites and pass them to some other ChildComponent , function, hook etc wherever you can make use of it.
Upvotes: 2