Skip to content
Advertisement

React Native, how to get values from multiple TextInputs into one object by pressing a Button?

I’m trying to put values from different TextInput‘s into 1 object. I’m new to React in general and don’t have a firm grasp of states yet. So far my code is like this:

function App() {

  const [enteredText, setEnteredText] = useState()
  const [firstText, setFirstText] = useState()
  const [secondText, setSecondText] = useState()

  function textChange(enteredText) {
    console.log(enteredText) //I want firstText and secondText here
  }
  return (
    <View style={styles.container}>

      <Text style={styles.header}>Great one!</Text>

      <TextInput 
        value={firstText}
        onChangeText={text=>setEnteredText(text)}
        style={styles.input} 
        placeholder='1st text' />

      <TextInput 
        value={secondText}
        onChangeText={text=>setEnteredText(text)}
        style={styles.input} 
        placeholder='2nd text' />

      <Button
        onPress={()=>textChange(enteredText)}
        title='Submit'
        color='orange' />

    </View>
  );
}

export default App;

Advertisement

Answer

You’re really close! What you want (enteredText) shouldn’t actually be a state. It logically flows from the first and second texts, so you can just have it be a constant.

Like this:

function App() {

  // changed the default state to be an empty string instead of
  // the default undefined value. But either would work.
  const [firstText, setFirstText] = useState("")
  const [secondText, setSecondText] = useState("")

  const enteredText = firstText + secondText

  // I'd probably rename this function to "handleSubmit"
  function textChange() {
    console.log(enteredText)
  }

  return (
    <View style={styles.container}>

      <Text style={styles.header}>Great one!</Text>

      <TextInput 
        value={firstText}
        onChangeText={text=>setFirstText(text)}
        style={styles.input} 
        placeholder='1st text' />

      <TextInput 
        value={secondText}
        onChangeText={text=>setSecondText(text)}
        style={styles.input} 
        placeholder='2nd text' />

      <Button
        onPress={textChange}
        title='Submit'
        color='orange' />

    </View>
  );
}

export default App;

Note how I changed the onChangeText callbacks for the TextInputs

So you set firstText and secondText in their respective onClicks. Whenever the state is updated, the component rerenders, and runs all the code in the function body. the constant enteredText will be created on each run, and will always be the most recent concatenation of the two states.

Hope this helps!

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement