Jim
Jim

Reputation: 669

How to handle multi input in react native generically?

I'd like to know why this code doesn't work :

<TextInput 
  style={style.inputLogin} 
  onChangeText={this.handleInputChange} 
  value={this.state.login} 
/>

with the function :

  handleInputChange = (event) => {
    console.log(event.target.name);
    this.setState({
      [name]: value
    });
    console.log("name => ", [name]);
    console.log("value => ", value);
  }

I tried many things but i can't get the targeted form. Should I make one function for each input ? seems to be stupid :/ event only contains the value of the form. Sure I could do this :

 <TextInput 
  style={style.inputLogin} 
  onChangeText={(value) => this.setState({value})) 
  value={this.state.login} 
/>

But this is not what I am looking for. I would like something more generic that works for every input

Please help me ;)

Upvotes: 0

Views: 1735

Answers (1)

Milore
Milore

Reputation: 1672

According to doc

onChangeText Callback that is called when the text input's text changes. Changed text is passed as a single string argument to the callback handler.

So the value passed by onChangeText is a string, not an event. In your handleInputChange you can treat text like

  handleInputChange = (text) => {
    console.log(text);
    // ...
  }

In order to handle multiple textInput with just a function, customize it like:

<TextInput 
  style={style.inputLogin} 
  onChangeText={(text) => this.handleInputChange(text, "Something to tell your function you're calling it from first textinput")} 
  value={this.state.login} 
/>

And then

  handleInputChange = (text, fromWhichTextInputAreYouCallingMe) => {
    console.log(text);
    this.setState({
      login: text
    });
  }

Upvotes: 1

Related Questions