Search code examples
javascriptreact-nativelambdatextinputeventhandler

How to handle a few TextInput by single handler in React Native without lambda function?


I need to handle a few inputs by single event handler in React Native app, but not to use lambda function, because it is forbidden in my app. With lambda function you can just sent the second parameter and it could be like this:

<TextInput
    placeholder = 'email'
    onSubmitEditing ={Keyboard.dismiss}
    onChangeText = {(text) => { this.handleTwoInputs(text, 'email'); }}
    autoCorrect = {false}
/>
<TextInput
    placeholder = 'name'
    onSubmitEditing ={Keyboard.dismiss}
    onChangeText = {(text) => { this.handleTwoInputs(text, 'name'); }}
    autoCorrect = {false}
/>
handleTwoInputs = (text, type) => {
  if(type === 'name'){
    this.inputName = text;
  } else {
   this.inputEmail = text;
 }
}

But how to do it without lambda function?


Solution

  • You don't need to use an arrow function:

    <TextInput
        placeholder = 'email'
        onSubmitEditing ={Keyboard.dismiss}
        onChangeText = {function(text) { this.handleTwoInputs(text, 'email'); }}
        autoCorrect = {false}
    />
    
    <TextInput
        placeholder = 'name'
        onSubmitEditing ={Keyboard.dismiss}
        onChangeText = {function(text) { this.handleTwoInputs(text, 'name'); }}
        autoCorrect = {false}
    />
    

    EDIT:

    OK I think I misunderstood the question. What you want to achieve is possible with onChange instead of onChangeText:

    <TextInput
        name = 'email_input'
        placeholder = 'email'
        onSubmitEditing ={Keyboard.dismiss}
        onChangeText = {handleTwoInputs}
        autoCorrect = {false}
    />
    
    <TextInput
        name = 'name_input'
        placeholder = 'name'
        onSubmitEditing ={Keyboard.dismiss}
        onChangeText = {handleTwoInputs}
        autoCorrect = {false}
    />
    
    handleTwoInputs = ({ nativeEvent }) => {
        const { eventCount, target, text } = nativeEvent
    
        if (target.name === 'name_input') {
          this.inputName = text;
        } else {
          this.inputEmail = text;
      }
    }