Undefined is not an object in React Native

2514 views react-native
0

Hi ninjas quick question I have a button which runs the following

onPress={this.props.productStore.closeModal}

but if I change the code to have a function:

closeModal() { this.props.productStore.closeModal; //alert('close modal'); }

and the button trigger onPress={this.closeModal} I get undefined is not an object. (this.props.productStore.closeModal is a mobx store which updates isModalVisible to false). If I uncomment alert in closeModal function the alert runs fine. Any help with resolving is appreciated. Thanks in advance

answered question

1 Answer

9

In the second variant, this.props is undefined because the function closeModal is not bound to this. Use either the arrow function syntax like below:

closeModal = () => {
  this.props.productStore.closeModal();
}

or bind the function to this.

onPress={this.closeModal.bind(this)}

Another problem that I noticed in the code is you are not calling the function. You should call the function.

this.props.productStore.closeModal();

posted this

Have an answer?

JD

Please login first before posting an answer.