YSA
YSA

Reputation: 879

Using colons within object destructuring

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

Answers (2)

GMaiolo
GMaiolo

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

justin.m.chase
justin.m.chase

Reputation: 13655

There are two basic ways to use the : in destructuring:

  1. destructuring sub objects
  2. aliasing a variable

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 :

Destructuring Sub Objects

const { component: { example } } = opts

// equivalent to
const example = opts.component.example

Aliasing a Variable

const { component: Component } = opts

// equivalent to:
const Component = opts.component

Both Combined

const { component: { example: Component } } = opts

// equivalent to
const Component = opts.component.example

Upvotes: 7

Related Questions