5

I am new to react js. I am working on a project and found this line

 const { var1, var2 } = this.props;  

Props which are comming in this component are

type PropsType = {
  var1: Array<any>,
  a: Array<any>,
  b: boolean,
  c: boolean,
  var2: (string) => void,
  d: () => void,
  e: () => void
};  

I am confused. What it means?

str
  • 33,096
  • 11
  • 88
  • 115
Pulkit Aggarwal
  • 1,779
  • 3
  • 17
  • 27
  • 1
    See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring – guest271314 Aug 02 '17 at 05:45
  • 1
    This is [object destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring). It's not got anything to do with React, it's a new language feature. – ivarni Aug 02 '17 at 05:47

3 Answers3

7
const { var1, var2 } = this.props;
// the same as
// const var1 = this.props.var1;
// const var2 = this.props.var2;

Have you tried to read the docs ?

Andrew
  • 6,470
  • 2
  • 21
  • 33
5

Well redundant information, but a revision for me. :) Anyways to start with, this is destructuring object assignment. What this means is that, this is a shorthand way to get the object properties' value from an object(such as this.props in here). So when you want to extract a property named 'var1' and 'var2' from the 'this.props', by writing the instruction -

const { var1, var2 } = this.props;

you ask for the property named 'var1' and 'var2' from 'this.props' to be stored in constants 'var1' and 'var2'. All other properties are simply ignored. And if any of the asked property names are not there, they are simply given 'unassigned' value.

After this, you may consider going through more details(magic of it!) here - MDN - object_destructuring

H S
  • 663
  • 3
  • 12
1

This is not directly related to React nor Redux. It is ES6 Object Destructuring assignment.

It means that you're assigning this.props.var1 and this.props.var2 to consts var1 and var2 respectively.

Community
  • 1
  • 1
Or B
  • 1,721
  • 13
  • 20