Search code examples
javascriptreactjsnativedestructuring

Can someone explain this react native code snippet to me?


I'm starting to look into react native, and for most of if, im doing good. But, although I know the concept of destructuring, I'm, scratching my head with this snippet of code.

var {
          View,
          Text,
          Image,
          Animated,
          StatusBarIOS,
          TouchableOpacity,
          DeviceEventEmitter
    } = React;

Can someone explain this to me?
Thanks!


Solution

  • This is just ES6 object destructuring. It is essentially creating a new variable for each one of the keywords listed in the object.

    It is equivilant to :

    var View = React.View;
    var Text = React.Text;
    var Image = React.Image;
    var Animated = React.Animated;
    

    .. etc

    If this is unclear at all look at a simple object as an example:

    const person = {
      name: 'sam',
      gender: 'male',
      age: 52
    }
    
    // create a variable for any property you want from the person object
    let { name, age } = person;
    
    console.log(name) // 'sam'
    console.log(age) // 52..
    

    As mentioned in the comments below because you are already using ES6 syntax you are most likely using a build tool or in an environment that supports ES6 and you should opt to use let or const instead of the ES5 var