Skip to content
Advertisement

How to get value from TextInput and set it with Button React Native?

I want to assign the username I get from a TextInput to a username variable via a button and output it in the text below. Meaning, if the user enters the username nothing happens but when the button is clicked the entered username will be shown in the text. How can I achieve this?

    function Login({navigation}) {

      return (
         <View style= {globalStyles.containerInput}>
             <TextInput 
                 style= {globalStyles.input} 
                 maxLength={20} 
                 minLegth={10} 
                 placeholder= "Username"
             />
         </View>
         <View style= {globalStyles.containerButton}>
             <Pressable 
                onPress={}
             >
                <Text style={globalStyles.text}>confirm</Text>
             </Pressable>
         </View>
         </View style={globalStyles.textOutput}>
             <Text style={globalStyles.text}>{usernameValue}</Text>
         </View>
      );
    }

Advertisement

Answer

You need to keep that value in state and you can use that state variable. And whenever you click that button you can use the state variable into userName For example

function Login({navigation}) {
     const [user, setUser] = useState("");
     const [userName, setUserName] = useState("");   
     const onValueChange = (text) => setUser(text); 
     const onButtonHandler = () => setUserName(user);
      return (
         <View style= {globalStyles.containerInput}>
             <TextInput 
                 style= {globalStyles.input} 
                 maxLength={20} 
                 minLegth={10} 
                 placeholder= "Username"
                 value={user}
                 onChangeText={onValueChange}
             />
         </View>
         <View style= {globalStyles.containerButton}>
             <Pressable 
                onPress={onButtonHandler}
             >
                <Text style={globalStyles.text}>confirm</Text>
             </Pressable>
         </View>
         </View style={globalStyles.textOutput}>
             <Text style={globalStyles.text}>{userName}</Text>
         </View>
      );
    }
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement