Okay, before we get into destructuring with React, let's find out a little about destructuring itself!
Destructuring was introduced in the 7th Edition of ECMAScript 2016 standard.
And accoriding to the MDN web docs about destructuring:
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values
from arrays, or properties from objects, into distinct variables.
With that knowledge; Let's say you had an object assigned to a variable:
var starShip = {
name: 'Enterprise',
registry: 1701,
sovereignty: 'Federation',
};
And you wanted to use a property of that object in a operation of somekind elsewhere,
You'd have to do something like this:
if (starShip.sovereignty === 'Federation') {
hailingFunction('peaceful')
}
Or if you wanted to assign it to a variable, you'd do this:
var registry = starShip.registry;
With the following expression, you can just use it without the starShip
identifier:
var { registry } = starShip;
`What is the registry of that ship helmsman?` // Klingon captain,
`${registry}, Sir!` //Klingon helmsman, outputs: 1701, Sir!
So essentially you create a new variable with the exact property name from the object you want:
For example this won't work:
var { starShipName, registryName, alliegence } = starShip;
That operation will yield three new variables with undefined
.
However this will work:
var { name: starShipName, registry: registryName } = starShip;
And in Arrays, instead of doing this:
var laptops = ['macbook-air', 'Chromebook', 'microsoft-laptop'];
var macBookAir = laptops[0];
var chromeLaptop = laptops[1];
var microSoftlaptop = laptops[2];
You can could destructure the value from the Array like so:
var [ macBookAir, chromeLaptop, microSoftlaptop ] = laptops;
So macBookAir
has been assigned the value from the first index in the laptops array which was macbook-air
, chromeLaptop
has the value of Chromebook
and microSoftlaptop has been assigned the string microsoft-laptop
.
You're probably thinking "Um, isn't this about destructuring in React???" Okay here we go!!!