Sinan Samet
Sinan Samet

Reputation: 6752

Can't setState in touchablehighlight onpress

When I try to set the state in touchablehighlight onpress my app crashes. This is what I got:

<TouchableHighlight onPress={this.setState({toggleCharacter: false})}>
    <Image style={styles.tekstballon} source={tekstballon} />
</TouchableHighlight>

My ultimate goal is to toggle toggleCharacter so if it is false I want to set it to true and if it's true I want to set it to false but I am not sure how to.

Upvotes: 4

Views: 8839

Answers (1)

user5004821
user5004821

Reputation:

You're invoking that setState call immediately on render. You need to wrap it in a function that will be called on onPress instead, ie:

<TouchableHighlight onPress={() => this.setState({toggleCharacter: false})}>

Keep in mind, the above is a bit frowned upon as it's creating a new function for every instance but it's just meant to give you an idea of why you're getting your error (a bit more performant to add it to the class itself.)

Edited to answer comment. The 'better' way of doing it mentioned above would be:

class myComponent extends React.Component {

  /*
    ...ctor and methods above
    The below assumes Property initializer syntax is available.
    If not, you need to autobind in the constructor
  /*
  handleOnPress = () => this.setState({ toggleCharacter: false })

  render() {
    return (
      <TouchableHighlight onPress={this.handleOnPress}>
        <Image style={styles.tekstballon} source={tekstballon} />
      </TouchableHighlight>
    );
  }
}

Upvotes: 9

Related Questions