Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Curly braces declaring a variable in React

Studying React right now. I am on the stage of Router and found some code in their documentation that I do not understand. (they use a lot of short-syntax operators and other stuff so it is hard to google or come up with idea what it is for).

So here is code:

const { from } = this.props.location.state || { from: { pathname: "/" } };
const { redirectToReferrer } = this.state;

While declaring "something" on the left it is inside of { }, why?

like image 287
Telion Avatar asked Dec 03 '22 11:12

Telion


2 Answers

for those who are really still confused about object destructuring, I can give an example:

suppose you have an object called car

const car = {
  type: 'van',
  model: 'honda',
  ...etc,
}

then instead of making a repetition of calling some variables inside the car object like this:

const type = car.type;
const model = car.model;

you can use destructuring object and write it in a more simple way:

const { type, model } = car;
like image 56
Zuzu Softman Avatar answered Dec 25 '22 00:12

Zuzu Softman


It is called object destructuring. It’s a JavaScript expression that allows us to extract data from arrays, objects, maps and sets. Please refer to link below for more details.

https://hacks.mozilla.org/2015/05/es6-in-depth-destructuring/

like image 45
ankita.gulati Avatar answered Dec 25 '22 00:12

ankita.gulati