0

Excuse the noobie question, but when I am going through the react native docs there are syntax differences to regular javascript. I am trying to figure out where the docs are that describe the syntax.

For example this statement

var {
  ActivityIndicatorIOS,
  StyleSheet,
  View,
} = React

And the use of the => operator in

  setToggleTimeout: function() {
    this.setTimeout(
      () => {
        this.setState({animating:     !this.state.animating});
        this.setToggleTimeout();
      },
      1200
    );
  },

2 Answers 2

4

Those are ECMAScript 6 features

Your first example is a destructuring assignment

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

And the second one is an arrow function

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

4

Accepted answer above is correct, but here are some examples:

First: an example of ES6 Destructuring:

var {
  ActivityIndicatorIOS,
  StyleSheet,
  View,
} = React

is exactly analogous to:

var ActivityIndicatorIOS = React.ActivityIndicatorIOS;
var StyleSheet = React.StyleSheet;
var View = React.View;

This is a nice shorthand approach. Of course, destructuring is more powerful than that and the Mozilla docs give further examples.

2nd: An example of an ES6 arrow function (or fat arrow function)

setToggleTimeout: function() {
    this.setTimeout(
      () => {
        this.setState({animating:     !this.state.animating});
        this.setToggleTimeout();
      },
      1200
    );
  },

Advantages are a less code to write, but a critical difference is that in arrow functions the 'this' is the same 'this' as the context it is written in. In other words, you don't have to use bind() anymore.

The bad old days:

setToggleTimeout: function() {
        this.setTimeout(
          function() {
            this.setState({animating:     !this.state.animating});
            this.setToggleTimeout();
          }.bind(this),
          1200
        );
      },
1
  • Very interesting this answer for mentioning the binding of this. It took me a while to discover that.
    – xabitrigo
    Apr 26, 2016 at 10:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.