james murphy
james murphy

Reputation: 1785

Pass event handler as props to react-native custom component

I have a custom component called MyButton.js

  <View style={{ alignItems: 'center', width: '100%' }}>
    <TouchableOpacity
      style={[styles.button, props.extraStyle]}
      onPress={props.onPress}
    >
      <Text style={styles.buttonText}>{props.children}</Text>
    </TouchableOpacity>
  </View>
);

I pass the onPress handler for the button via props from parent SignUp.js

  <MyButton
    extraStyle={{ backgroundColor: '#03A9F4' }}
    onPress={this.signUpUser}
  >
    SIGN UP
  </MyButton>

Problem is that my signUpUser function (also in SignUp.js) needs to be passed 3 arguments

signUpUser = (userName, email, password) => {
    try {
      //handle password<6 and bad email format etc pls!!!!
      Firebase.auth()
        .createUserWithEmailAndPassword(email, password)
        .then((user) => {
          console.log('User created in firebase', user);
          //update FB with userNameNode......and default values for profile
          Firebase.database()
            .ref('profiles/users/' + user.user.uid)
            .set({
              active: false,
              emailAddress: email,
              userName: userName,
              userId: user.user.uid,
              ................
              ................

If I change the onPress prop of MyButton compoment as below to pass args....I get error in that it logs user in before theyve even pressed the button

<MyButton
    extraStyle={{ backgroundColor: '#03A9F4' }}
    onPress={this.signUpUser(
      this.state.userName,
      this.state.email,
      this.state.password,
    )}
  >
    SIGN UP
  </MyButton>

Can someone please help? Ive been up all night with this lol

Upvotes: 0

Views: 1129

Answers (1)

Fatih Aktaş
Fatih Aktaş

Reputation: 1564

try to change

onPress={this.signUpUser(blabla)}

to

onPress={() => this.signUpUser(blabla)}

There is a similar post here, React Native onPress being called automatically

Upvotes: 2

Related Questions