Reputation: 879
I'm still unfamiliar with all the magic of ES6. I saw this code in an online article and I'm not sure how PrivateRoute
is destructuring the input props. what does component: Component
do in this context?
const PrivateRoute = ({ component: Component, ...rest }) => (
// Code here
)
I understand that I can do something like this to destructure an object
obj = {firstName: 'John', lastName: 'Doe'};
{first, last} = obj;
and have first = 'John'
, last = 'Doe'
; however, I got confused with the introduction of a colon in the example code.
Here's a link to the full article: https://tylermcginnis.com/react-router-protected-routes-authentication/
Upvotes: 3
Views: 1126
Reputation: 4628
It's to use a different name for a property obtained by destructuring.
let obj = {
a: 'thing A',
b: 'thing B'
}
let { a: newVariable } = obj
console.log(newVariable) // outputs: "thing A"
See MDN docs for Assigning to new variable names
Upvotes: 3
Reputation: 13655
There are two basic ways to use the :
in destructuring:
If the right hand side of the :
is an object or array then you are destructuring a sub-object. If the right hand side is an identifier then you are aliasing the key on the left hand side of the :
const { component: { example } } = opts
// equivalent to
const example = opts.component.example
const { component: Component } = opts
// equivalent to:
const Component = opts.component
const { component: { example: Component } } = opts
// equivalent to
const Component = opts.component.example
Upvotes: 7