Search code examples
react-nativetextinputreact-native-textinput

How to get values from TextInput


I'm stuck in a apparently simple function. How can I get a value (string) from a TextInput?

Here an extract of the code:

const Insert = props => {
  const [enteredName, setEnteredName] = useState();


const sendValues = (enteredName) => {

    console.log(enteredName);

  };

 <TextInput
          placeholder="Your Name"
          blurOnSubmit
          autoCorrect={false}
          maxLength={30}
          autoCapitalized="words"
          placeholderTextColor="#777"
          value={enteredName}
          onChangeText={text => setEnteredSurname(text)}

        />

        <View>
          <Button title="Submit" onPress={sendValues(enteredName)} />

I get the typing when I type but it doesn't submit anything.

Any idea about it??

Thanks in advance!


Solution

  • You should transform your onPress from an expression to a function and init your state

    const Insert = props => {
      const [enteredName, setEnteredName] = useState(''); //INIT TO EMPTY
    
    
    function sendValues(enteredName) {
        console.log(enteredName);
    };
    
     <TextInput
        placeholder="Your Name"
        blurOnSubmit
        autoCorrect={false}
        maxLength={30}
        autoCapitalized="words"
        placeholderTextColor="#777"
        value={enteredName}
        onChangeText={text => setEnteredSurname(text)} />
    
        <View>
          <Button title="Submit" onPress={() => sendValues(enteredName)} /> //Function not expression
        </View>