user3802348
user3802348

Reputation: 2592

Create Alert dialog within a React Native function?

In my React-native app, I have a screen where when the user presses a button to submit an answer, I want an alert dialog to appear telling them whether the answer is correct or incorrect. So, I am calling a function in the onPress method of the TouchableHighlight button, and within that function I specify the alert dialog. However, this causes the Alert dialog to reappear over and over, as the function is continuously called in each frame. How can I get the function to only be called once?

Relevant code: render function

render: function() {                    
    return (
        <View style={styles.container}>
            <Text style={styles.title}>{this.state.title}</Text>
            <TouchableHighlight style = {styles.button}
                    onPress={this.onSubmitPressed()}
                    underlayColor='#99d9f4'>
                    <Text style = {styles.buttonText}>SUBMIT</Text>
            </TouchableHighlight>
        </View>
    );
},

Validation function:

onSubmitPressed: function() {
    if (this.checkSolution) {
        Alert.alert(
            'Alert title',
            "Correct!"
        );
    }
    else {
        Alert.alert(
            'Alert title',
            "Incorrect!"
        );
    }
},

Upvotes: 1

Views: 2722

Answers (1)

Daniel Basedow
Daniel Basedow

Reputation: 13396

You are calling onSubmitPressed in your render function. Change onPress={this.onSubmitPressed()} to onPress={this.onSubmitPressed} (note the missing parentheses).

Upvotes: 5

Related Questions