Search code examples
functionreact-nativeecmascript-6google-places-apionpress

React Native /ECMAScript 6 Syntax


I can't find great documentation on ECMAScript 6 syntax breakdown. The short hand is awesome but difficult to read sometimes. Can anyone break down the onPress function for me? Or point me to some good documentation with the break down of syntax?

I understand this as: onPress we will run a function that take in params of data and null and we will print it out after we have a response. Data and details are the responses from the google api so I have to assume that we aren't actually setting details to null. I just don't understand the function syntax.

<GooglePlacesAutocomplete
    placeholder='Search'
    minLength={2} // minimum length of text to search
    fetchDetails={true}
    onPress={(data, details = null) => { // 'details' is provided when fetchDetails = true
        console.log(data, details);
    }}

Solution

  • The null value being passed to the argument of the function is a default parameter.

    Here's how arrow functions work.

    1. An empty function block looks like this -

      () => {}  
      

      which is equivalent to -

      function () {}
      
    2. If you add parameters, it looks like -

      (param1, param2) => {}
      

      which is equivalent to

      function(param1, param2) {}
      
    3. And with a default parameter, it looks like -

      (param1, param2 = 2) => { return param1 + param 2}
      

      which is equivalent to

      function(param1, param2 = 2){
       return param1 + param2;
      }
      

      A call to this function can be made with 1 or 2 paramters. If made with a single parameter, it will take param2's value as 2 in the above example by default.

    So, in your case, you're setting the value to null as a default parameter, if nothing comes in the details of the onPress event.