ORStudios
ORStudios

Reputation: 3233

React Native Maximum Call Stack Exceeded When Passing Parameter

I am getting a strange error. I have the following bit of code.

<View style={styles.optionBarItem}>
                        <TouchableOpacity style={styles.optionBarItemWrapper} onPress={this.onIconPress("Events")} >
                          <Image source={imageMessages} style={{width: 20, height: 20}}/>
                          <Text style={[styles.optionBarItemText]}>MESSAGES(3)</Text>
                        </TouchableOpacity>
                    </View>



onIconPress( type = "" ){

    if(type == "Events"){
        this.setState({  iconOn: "Events"  });
    }
    else if(type == "Messages"){
        this.setState({  iconOn: "Messages"  });
    }
    else if(type == "Person"){
        this.setState({  iconOn: "Person"  });
    }
    else if(type == "Parcel"){
        this.setState({  iconOn: "Parcel"  });
    }

  }

If I run the above code the simulator stops and throws out a Maximum Call Stack exceeded error. enter image description here

However if I make the following change and don't include the parameter it runs fine.

onPress={this.onIconPress()

Can anyone explain why this is happening?

Thanks

Upvotes: 0

Views: 348

Answers (1)

madox2
madox2

Reputation: 51911

You are calling onIconPress function in each render and passing the result to onPress prop. So in the render is called onIconPress, which sets state and triggers other render, which calls onIconPress again and so on... Therefore Maximum Call Stack exceeded error.

You need to pass a function here which will be called on press event. For example you can create inline arrow function which calls onIconPress with parameter:

onPress={() => this.onIconPress("Events")}

Upvotes: 2

Related Questions