Destructuring is a small but a great concept that applies to arrays and objects both.
Destructuring feature was added in the ES6 specification of JavaScript.
In short, destructuring allows you to destructure values from objects and arrays.
Destructuring an object
In React, you pass the data via props to the components and use it like props.name, props.address via a dot operator.
Here’s an example of props object:
...
props = {
name: 'Yogesh Chauhan',
address: 'Some Address',
}
...
Usually we use props like this:
...
{props.name}'s address is {props.address}.
...
If you don’t want to use props.abc, props.xyz then you can just save the data into variables like this:
...
let name = props.name;
let address = props.address;
...
Now you can use those variables instead.
...
{name}'s address is {address}.
...
That’s not it.
Destructuring makes your job easy when it comes to the assignment of variables.
You can just extract the values of an object’s properties and assign them to separate variables like this:
...
let { name, address } = props
...
The order of those variables inside the bracket doesn’t matter!
That’s not it!
You can just directly pass that bracket with the variable names instead of props and it will work like a charm!
Let’s revisit the component helper function example.
array components destructuring examples objects props