Function firing when it wants to. How should I fix this? Function firing when it wants to. How should I fix this? reactjs reactjs

Function firing when it wants to. How should I fix this?


Replace it with this._textRoomPress.bind(this)

It is not firing arbitrarily, it is firing every time a render is issued. That happens because whatever you pass to an object as a prop is evaluated before being passed (as the parameters of a function are, basically), and so what you are passing is the returning value of the function, which of course is not what you want. By passing this._textRoomPress (with the optional bind in case that you want to keep the context of the object), you pass a reference to the function that will be later called by the component on the appropriate time (when the element is pressed).


Since you're using createClass and not the es6 syntax, all the methods are already autobinding to the Component. Simply just change your onPress to:

onPress={this._textRoomPress}>

If you use onPress={this._textRoomPress()}> It is instantly invoking that function anytime your component gets rendered.


In javascript you use <function name>() to invoke a function... What you are doing here is simply invoking that function every time that _renderTextRoom()gets called rather than assigning it to the onPress prop. What I would suggest is that you pass an anonymous function in as the prop (without calling it) which than returns the invocation of this._textRoomPress. ES6 arrow functions make this super easy because they do not bind their own this more info here

  <View style={styles.buttonContainer}>    <TouchableHighlight      style={styles.button}      onPress={() => this._textRoomPress()}>      <Text style={styles.bgWhite}>Send</Text>    </TouchableHighlight>  </View>