Skip to content Skip to sidebar Skip to footer

Method Inside Anonymous Function Inside Map Is Undefined

How does one invoke handleButtonPress inside the message map in this example React component? import React, { Component } from 'react'; import {View, Text, TouchableOpacity} from '

Solution 1:

The problem is that Array.prototype.map doesn't bind a this context unless explicitly told to. From the documentation:

If a thisArg parameter is provided to map, it will be passed to callback when invoked, for use as its this value. Otherwise, the value undefined will be passed for use as its this value.

Since you never specify a this value, it is undefined, and doing thus the this that is bound to the anonymous function in onPress is undefined. That throws the error because there is no function handleButtonPress of undefined. This means you need to pass a this context to map, and from the documentation:

Syntax

arr.map(callback[, thisArg])

This will be applied like so:

{
    this.state.messages.map(function(message, index){
        return (
          <TouchableOpacitykey={index}onPress={function(){this.handleButtonPress(message) }.bind(this) }><Text>Press Me</Text></TouchableOpacity>
        )
    }, this) //Notice the `this` here, this is the optional thisArg which is used as the `this` value in the callback.
}

The this is the class when passed to map. It will then be bound to onPress's event handler (the anonymous function) and then call correctly. (Note: You should probably bind your methods once in the constructor because if you do it as you do now, a new method will be created every time the event is triggered.)


Actually, without a thisArg passed, the this value is determined as usual. Since this in regular functions is window (undefined in strict mode, which is default for classes), this isn't what you think it is.

Post a Comment for "Method Inside Anonymous Function Inside Map Is Undefined"