Gui Be
Gui Be

Reputation: 27

How to get a text input value in a view?

I'm working on React Native and I'm quite a beginner so sorry in advance if my question is particularly easy.

I'm working in a view (Home.Js), not in App.Js for the moment. In this Home view I have a text input (username) and I want to get the value entered by the user when he clicks on a button. I watched explaining videos but they explain how to do it in App.Js and it doesn't work when i implement it in my view. Here is my code. Thank you


#Here We Are in my Home View (Home.Js) not App.Js

import React from 'react';
import { Image, ImageBackground, StyleSheet, View, Text, TouchableOpacity, TextInput, Button } from 'react-native';

function Home(props) {

return (
    <View style={styles.container}>
        <View style={styles.header}>
            <Image source={require('../assets/logo.png')}
            style={styles.Logo}/>
            <Image source={require('../assets/Joiny.png')}
            style={styles.Logo}/>
        </View>
        <View style={styles.footer}>
            <TextInput>Username</TextInput>
        </View>

    </View>
);

};

Upvotes: 0

Views: 550

Answers (2)

Nooruddin Lakhani
Nooruddin Lakhani

Reputation: 6967

Try this way

import React from 'react';
import { View, Text, TouchableOpacity } from 'react-native';

function Home(props) {

const [text, setText] = useState('');

return (
    <View style={styles.container}>
       ......
        <View style={styles.footer}>
            <TextInput onChangeText={text => setText(text)}>Username</TextInput>
        </View>
        <TouchableOpacity onPress={() => alert(TouchableOpacity)}>
            <TextInput onChangeText={text => setText(text)}>Username</TextInput>
        </TouchableOpacity>

    </View>
);
export default App;

Upvotes: 1

Mehran Khan
Mehran Khan

Reputation: 3636

you can set the value in state and retrieve value from state when press button

export default function App() {
   const [value, onChangeText] = React.useState('');
  return (
    <View style={styles.container}>
     
    <TextInput
      style={{ height: 40, borderColor: 'gray', borderWidth: 1,marginBottom:30 }}
      onChangeText={text => onChangeText(text)}
      value={value}
      placeholder="Username"
    />
    <Button onPress={() => {
      alert(value)
    }}
  title="Learn More"
  color="#841584" />
  
    </View>
  );
}

snack link https://snack.expo.io/La32SNKz5

Upvotes: 0

Related Questions