user8138816
user8138816

Reputation:

How to Pass onPress to custom component and get the values back to calling component?

I cloned a react-native GitHub source. In that, for login functionality, they are using for two files on for View and one for functionality.

Here is login.js

class Login extends Component {

 submitLogin(email, password) {
   alert('clickedLogin');
  }

render() {
return (
  <LoginView onPress={this.submitLogin.bind(this)} 
             onSignupPress={this.displaySignupView.bind(this)}/>
   )
 }
}

Here is LoginView.js -> to which the above onPress and onSignupPress are sent and it has form elements here.

 class LoginView extends Component {
   state = {
      email: '',
      password: '',
      isAuthenticating: false,
      error: ''
     }     

  render() {
    return (
     <View>
        <TextInput
          style={[styles.input, styles.whiteFont]}
          placeholder="Email"
          placeholderTextColor="#FFF"
          underlineColorAndroid='transparent'
          onChangeText={(email) => this.setState({email})}
          value={this.state.email}/>
       <TextInput
          secureTextEntry={true}
          style={[styles.input, styles.whiteFont]}
          placeholder="Password"
          placeholderTextColor="#FFF"
          onChangeText={(password) => this.setState({password})}
          value={this.state.password}/>
      <TouchableOpacity
          style={styles.signin}
          onPress={this.props.onPress.bind(this, this.state.email, this.state.password)}>
          <Text style={styles.signinText}>Sign In</Text>
        </TouchableOpacity>
     </View>
   )
  }
 }

When login button is hitting submitLogin function is getting called an alert is coming but I couldn't find a way to get the entered email and password in LoginView input elements to the Login file and alert it in submitLogin.

How can I do that?

Upvotes: 1

Views: 2204

Answers (1)

Haythem Farhat
Haythem Farhat

Reputation: 797

You shouldn't be using bind on this.props.onPress, otherwise it will not reference the original parent function, What you may want to do to pass the email and password is something like this :

in the LoginView.js :

  <TouchableOpacity
      style={styles.signin}
      onPress={()=>this.props.onPress(this.state.email,this.state.password)}>

      ...

    </TouchableOpacity>

To learn more about how bind works i recommend reading this article : https://www.codementor.io/niladrisekhardutta/how-to-call-apply-and-bind-in-javascript-8i1jca6jp

Upvotes: 2

Related Questions