Search code examples
javascriptreactjsreact-native

How to get the TextInput value in React Native


I have this code where I'm getting a user input. But when I'm console logging it to check it I'm getting an object of type undefined. I'm providing my code here. How can I correct my code so that this bug is fixed?

export default function App() {
  const [enteredGoal, setGoal] = useState('');
  const goalInputHandler = (enteredText) => {
    setGoal(enteredText);
  };
  const addGoalHandler = () => {
    console.log(enteredGoal);
  }
  return (
    <View style={styles.screen}>
      <StatusBar style="auto" />
      <View style={styles.inputTextContainer}>
        <TextInput
        style={styles.TextInput}
          placeholder="Course Goal"
          onChange={goalInputHandler}
          value={enteredGoal}
        />
        <Button title="ADD"  onPress={addGoalHandler} />
      </View>
    </View>
  );
}


Solution

  • You have to use the onChangeText prop

    onChangeText={(text)=>goalInputHandler(text)}
    

    This will pass the current text to goalInputHandler function