learner62
learner62

Reputation: 610

How to handle multiple TextInput with single Handler?

I have 2 Textinput and I want, one handler which can grab a value from multiple Textinput



export default class App extends Component {
state = { 
      text: '',
      textTwo:''
       };
  }

  handleChange=(text)=>{
    this.setState({
      text
    })
  }

      <View style={styles.container}>
        <TextInput style={{ width: 300, height: 50, backgroundColor: 'gray', fontWeight: 'bold', textColor: 'white', fontSize: 30,marginTop:20
          }}
          placeholder="vrdth No."
          onChangeText={(text)=>this.handleChange(text)}
        />
        <TextInput style={{ width: 300, height: 50, backgroundColor: 'gray', fontWeight: 'bold', textColor: 'white', fontSize: 30,marginTop:20
          }}
          placeholder="vrdth No."
          onChangeText={(text)=>this.handleChange(text)}
        />

        <Text style={{ padding: 10, fontSize: 16, fontWeight: 'bold' }}>
          {this.state.text}
        </Text>
        <Text style={{ padding: 10, fontSize: 16, fontWeight: 'bold' }}>
          {this.state.textTwo}
        </Text>
      </View>

"I expect state needs to be updated when I input on it with a single handler I have added my code in snack.expo.io. please check below for ref link " check for ref snack.expo.io

Upvotes: 0

Views: 439

Answers (1)

Charlie
Charlie

Reputation: 1042

There are many ways to do it, the easier i can think of right now is to pass a second param to your handler function, and to take advantage of es6 destructuring

Your calls to onChangeText will be like this

onChangeText={(text)=>this.handleChange(text, 'text')}

onChangeText={(text)=>this.handleChange(text, 'textTwo')}

and then your handler will use the destructure to apply that to text to the correct state

  handleChange=(text, stateProp)=>{
    this.setState({
      [stateProp]: text
    })
  }

You can read more about this in this link

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Computed_object_property_names_and_destructuring

Upvotes: 1

Related Questions