How to get values from TextInput - react-native

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!

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>

class AwesomeProject extends Component {
constructor(props){
super(props)
this.state = {
username: '',
password: '',
}
}
_handlePress() {
console.log(this.state.username);
console.log(this.state.password);
}
render() {
return (
<ScrollView style={styles.content}>
<View style={styles.content}>
<Text style={styles.welcome}>
Create Account
</Text>
<Text style={styles.textStyle}>
Name
</Text>
<TextInput
style={styles.textInputStyle}
placeholder="Enter Name"
returnKeyLabel = {"next"}
onChangeText={(text) => this.setState({username:text})}
/>
<Text style={styles.textStyle}>
Name
</Text>
<TextInput
style={styles.textInputStyle}
placeholder="Enter Name"
returnKeyLabel = {"next"}
onChangeText={(text) => this.setState({password:text})}
/>
<Button
onPress={() => this._handlePress()}
style={styles.buttonStyle}>
Submit
</Button>
</View>
</ScrollView>
);
}
}

Try this, you have to use it like this :
import React, { useState } from 'react';
import {Text, View,TextInput,Button} from 'react-native';
export default Example = () => {
const [enteredName, setEnteredName] = useState('');
sendValues = (enteredName) =>{
console.log(enteredName);
};
return (
<View>
<Text>Hey</Text>
<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)} />
</View>
</View>
);
}

Related

how to submit a form in react native and submit to a post api

I want to save the values from all input fields to getdata(), but I am getting undefined value
export default function Signupfor(props) {
// const phoneInput = useRef < PhoneInput > null;
const [text, setTextname] = useState();
function getdata() {
console.log('dsd');
console.log(text);
}
const {userInfo, log} = props?.route?.params;
console.log(log.name);
return (
<View style={styles.prheight}>
<View style={styles.form}>
<Text style={styles.r}>One Last Step</Text>
<TextInput
style={styles.forminput}
label="Name"
value={userInfo.user.name}
onChangeText={text => setTextname(text)}
/>
<TextInput
style={styles.forminput}
label="Email"
value={userInfo.user.email}
onChangeText={text => setTextemail(text)}
/>
<TextInput
style={styles.forminput}
label="Whatsapp Number"
keyboardType="numeric"
value={userInfo.user.number}
onChangeText={text => setTextnumber(text)}
// value={this.state.myNumber}
maxLength={10} //setting limit of input
/>
</View>
<View style={styles.buttonw}>
<Button color="#7743DB" title="Lets Go" onPress={() => getdata()} />
</View>
</View>
);
}
Here, name and email should not be able to be edited. I want to pass the value from value={userInfo.user.name} to the getdata()
you can use formik package for making form in react native
Installation
yarn add formik
Usage
import { Formik } from "formik";
export default function Signupfor(props) {
const { userInfo, log } = props?.route?.params;
console.log(log.name);
return (
<Formik
initialValues={{
name: userInfo.user.name,
email: userInfo.user.email,
number: userInfo.user.number,
}}
onSubmit={async (values, actions) => {
try {
console.log("name", values.name);
console.log("phone", values.number);
const params = {
full_name: values.name,
email: values.email,
phone_number: values.number,
};
} catch (error) {
let message = error.message;
console.log(message)
} finally {
actions.setSubmitting(false);
}
}}
>
{({
handleChange,
setFieldValue,
handleSubmit,
values,
errors,
touched,
isSubmitting,
}) => (
<View style={styles.prheight}>
<View style={styles.form}>
<Text style={styles.r}>One Last Step</Text>
<TextInput
style={styles.forminput}
label="Name"
value={values.name}
onChangeText={handleChange("name")}
/>
<TextInput
style={styles.forminput}
label="Email"
value={values.email}
onChangeText={handleChange("email")}
/>
<TextInput
style={styles.forminput}
label="Whatsapp Number"
keyboardType="numeric"
value={values.number}
onChangeText={handleChange("number")}
// value={this.state.myNumber}
maxLength={10} //setting limit of input
/>
</View>
<View style={styles.buttonw}>
<Button
color="#7743DB"
title="Lets Go"
onPress={() => handleSubmit()}
/>
</View>
</View>
)}
</Formik>
);
}
Your original method doesn't populate the state unless you edit the text input field, this is because your initialState doesn't have a value to start with. so firing getData() is reading empty state if the fields havent been changed.
onChangeText={text => setTextname(text)}
Only fire if you edit the textInput field.
Also I think you might be missing props, so first check if you are getting the correct data from props by logging it.
Once you have confirmed the props are available.
Set the initialState for name to userInfo.user.name
const { userInfo } = props?.route?.params;
const [name, setName] = useState(userInfo.user.name);
Then pass the state name to your TextInput and it should populate the value by reading from state.
return (
<>
<TextInput
placeholder="name"
value={name}
onChangeText={(text) => setName(text)}
/>
<Button title="Submit" onPress={() => getData()} />
</>
)
Make sure to create states for any additional values you wish to save.
const [name, setName] = useState(userInfo.user.name);
const [email, setEmail] = useState(userInfo.user.email);
You can use a library like https://react-hook-form.com to check an example with react native on video.
Or you can right it yourself, in the example below any time you need access to input values you can read it from text and number
const UselessTextInput = () => {
const [text, onChangeText] = useState("Useless Text");
const [number, onChangeNumber] = useState(null);
return (
<SafeAreaView>
<TextInput
style={styles.input}
onChangeText={onChangeText}
value={text}
/>
<TextInput
style={styles.input}
onChangeText={onChangeNumber}
value={number}
placeholder="useless placeholder"
keyboardType="numeric"
/>
</SafeAreaView>
);
};
You can do something like this!!
export default function Signupfor(props) {
const {userInfo, log} = props?.route?.params;
const [name, setName] = useState(userInfo?.user?.name);
const [phone, setPhone] = useState(userInfo?.user?.number);
function getdata() {
console.log("name",name)
console.log("phone",phone)
}
return (
<View style={styles.prheight}>
<View style={styles.form}>
<Text style={styles.r}>One Last Step</Text>
<TextInput
style={styles.forminput}
label="Name"
// this value must be same with useState
value={name}
onChangeText={text => setName(text)}
/>
<TextInput
style={styles.forminput}
label="Mobile"
value={phone}
onChangeText={text => setPhone(text)}
/>
</View>
<View style={styles.buttonw}>
<Button color="#7743DB" title="Lets Go" onPress={() => getdata()} />
</View>
</View>
);
}
Same goes for email.

Flatlist doesn't display the list from useContext

In react native app, I have a home screen and a second screen that the user uses to add items that should be displayed on the home screen. I am using context to save the list of items. The problem is when I add items to the second screen and go to the home screen. The displayed list is empty.
Any help to explain why this happens and how to handle it? Here's the
Data Context
export const ExpenseContext = createContext();
App.js
const Stack = createNativeStackNavigator();
function App() {
const [expenseList, setExpenseList] = useState([]);
return (
<NavigationContainer>
<ExpenseContext.Provider value={{ expenseList, setExpenseList }}>
<Stack.Navigator>
<Stack.Screen
name="Home"
component={Home}
options={{ title: "Dashboard" }}
/>
<Stack.Screen
name="AddItem"
component={AddItem}
options={{ title: "CashFlowCreate" }}
/>
</Stack.Navigator>
</ExpenseContext.Provider>
</NavigationContainer>
);
}
export default App;
Home.js
function Home({ route, navigation }) {
const { expenseList } = useContext(ExpenseContext);
return (
<View style={styles.container}>
<Text style={styles.text}>Budget:</Text>
<Button title="+" onPress={() => navigation.navigate("AddItem")} />
<View>
<FlatList
style={styles.listContainer}
data={expenseList}
renderItem={(data) => <Text>{data.item.name}</Text>}
/>
</View>
</View>
);
}
export default Home;
AddItem.js
function AddItem({ navigation }) {
const { expenseList, setExpenseList } = useContext(ExpenseContext);
const [name, setName] = useState("");
const [amount, setAmount] = useState("");
const itemsList = expenseList;
return (
<View style={styles.container}>
<TextInput
style={styles.input}
onChangeText={(name) => setName( name )}
value={name}
placeholder="Name"
keyboardType="default"
/>
{name === "" && (
<Text style={{ color: "red", fontSize: 12, paddingLeft: 12 }}>
Name is required
</Text>
)}
<TextInput
style={styles.input}
onChangeText={(amount) => setAmount( amount )}
value={amount}
placeholder="Amount"
keyboardType="numeric"
/>
{amount === "" && (
<Text style={{ color: "red", fontSize: 12, paddingLeft: 12 }}>
Amount is required
</Text>
)}
<Button
title="Add"
style={styles.btn}
onPress={() => {
if (name === "" || amount === "") {
alert("Please Enter the required values.");
} else {
itemsList.push({
name: name,
amount: amount,
});
setExpenseList(itemsList);
}
}}
/>
<Button
title="View Dashboard"
style={styles.btn}
onPress={() => {
navigation.navigate("Home");
}}
/>
</View>
);
}
export default AddItem;
I solve it, in AddItem component remove const itemsList = expenseList; and onPress add button it should be like that instead
onPress={() => {
name === "" || amount === ""
? alert("Please Enter the required values.")
: setExpenseList([
...expenseList,
{
key:
Date.now().toString(36) +
Math.random().toString(36).substr(2),
name: name,
amount: amount,
},
]);
}}
I added the key because I needed later on.
There are several areas of issues in your code. One issue I can see is in AddItem. When you set:
const itemsList = expenseList
I think you did this for:
itemsList.push({
name: name,
amount: amount,
});
But you should look at the spread operator and try:
setExpenseList(...expenseList, {
name,
amount,
})
rewrite of AddItem.js:
function AddItem({ navigation }) {
const { expenseList, setExpenseList } = useContext(ExpenseContext)
const [name, setName] = useState('')
const [amount, setAmount] = useState('')
return (
<View style={styles.container}>
<TextInput style={styles.input} onChangeText={setName} value={name} placeholder='Name' keyboardType='default' />
{name === '' ? <Text style={styles.err}>Name is required</Text> : null}
<TextInput style={styles.input} onChangeText={setAmount} value={amount} placeholder='Amount' keyboardType='numeric' />
{amount === '' ? <Text style={styles.err}>Amount is required</Text> : null}
<Button
title='Add'
style={styles.btn}
onPress={() => {
name === '' || amount === ''
? alert('Please Enter the required values.')
: setExpenseList(...expenseList, {
name: name,
amount: amount,
})
}}
/>
<Button title='View Dashboard' style={styles.btn} onPress={() => navigation.navigate('Home')} />
</View>
)
}
export default AddItem
In your Home.js your FlatList it's missing the keyExtractor and you're trying to declare a prop of title outside of <Text>, rewrite:
function Home({ navigation }) {
const { expenseList } = useContext(ExpenseContext);
return (
<View style={styles.container}>
<Text style={styles.text}>Budget:</Text>
<Button title="+" onPress={() => navigation.navigate("AddItem")} />
<View>
<FlatList
style={styles.listContainer}
data={expenseList}
keyExtractor={(_,key) => key.toString()}
renderItem={(data) => <Text>{data.item.name}</Text>}
/>
</View>
</View>
);
}
export default Home;
Edit:
Answering to the comment. My understanding of the docs that is incorrect because keyExtractor is for identifying the id and by your commented code unless your passed in data to FlatList has a property of key then that wont work.
Also if key is not a string it should be:
keyExtractor={(item) => item.key.toString()}

React Native - Access Wrapped Component Methods

I'm trying to drive focus to the second field in a form using custom input components. However, I can't seem to access the focus() or other methods of TextInput which I am extending in the custom class. I have seen some information on ref forwarding as well as implementing the focus() function within the class but have not been able to get either working yet.
Whenever I try to hit the "next" button on the keyboard, it says that focus is not a function. Any help or reference would be appreciated.
<View>
<CustomInput
onRef={ref => (this.child = ref)}
autoCapitalize={'none'}
returnKeyType={'next'}
autoCorrect={false}
onSubmitEditing={() => this.lastNameInput.focus()}
updateState={(firstName) => this.setState({firstName})}
blurOnSubmit={false}
/>
<CustomInput
onRef={ref => (this.child = ref)}
autoCapitalize={'none'}
returnKeyType={'done'}
autoCorrect={false}
updateState={(lastName) => this.setState({lastName})}
ref={(input) => { this.lastNameInput = input; }}
onSubmitEditing={(lastName) => this.setState({lastName})}
/>
</View>
export default class UserInput extends Component {
render() {
return (
<View style={styles.inputWrapper}>
<TextInput
style={styles.input}
autoCorrect={this.props.autoCorrect}
autoCapitalize={this.props.autoCapitalize}
returnKeyType={this.props.returnKeyType}
placeholderTextColor="white"
underlineColorAndroid="transparent"
onChangeText={(value) => this.props.updateState(value)}
blurOnSubmit={this.props.blurOnSubmit}
/>
</View>
);
}
}
you need to do some changes in both components. according to https://stackoverflow.com/a/49810837/2083099
import React, { Component } from 'react'
import {View,TextInput} from 'react-native';
class UserInput extends Component {
componentDidMount() {
if (this.props.onRef != null) {
this.props.onRef(this)
}
}
onSubmitEditing() {
if(this.props.onSubmitEditing){
this.props.onSubmitEditing();
}
}
focus() {
this.textInput.focus()
}
render() {
return (
<View style={{ flex: 1 }}>
<TextInput
style={{ height: 100, backgroundColor: 'pink' }}
autoCorrect={this.props.autoCorrect}
autoCapitalize={this.props.autoCapitalize}
returnKeyType={this.props.returnKeyType}
placeholderTextColor="white"
underlineColorAndroid="transparent"
onChangeText={(value) => this.props.updateState(value)}
blurOnSubmit={this.props.blurOnSubmit}
ref={input => this.textInput = input}
onSubmitEditing={this.onSubmitEditing.bind(this)}
/>
</View>
);
}
}
export default class OrderScreen extends Component {
constructor(props) {
super(props);
this.focusNextField = this.focusNextField.bind(this);
this.inputs = {};
}
focusNextField(id) {
this.inputs[id].focus();
}
render() {
return (
<View style={{ flex: 1 }}>
<UserInput
autoCapitalize={'none'}
returnKeyType={'next'}
autoCorrect={false}
updateState={(firstName) => this.setState({ firstName })}
blurOnSubmit={false}
onRef={(ref) => { this.inputs['projectName'] = ref; }}
onSubmitEditing={() => {this.focusNextField('projectDescription');}}
/>
<UserInput
onRef={(ref) => {this.inputs['projectDescription'] = ref}}
autoCapitalize={'none'}
returnKeyType={'done'}
autoCorrect={false}
updateState={(lastName) => this.setState({ lastName })}
/>
</View>
)
}
}

state disappears when method is call

I'm working on a class project and my state is disappearing. After componentDidMount console.log(this.state) is fine. I initiate setInterval and call inc(). Somehow when I enter inc() the state gets wiped out.
import React from 'react';
import { TextInput,Button,StyleSheet, Text, View } from 'react-native';
import styles from './styles/styles.js';
debug=true
export default class App extends React.Component {
constructor(){
super()
this.state={timer:'WORK',
workTime: 25*60+0,
breakTime: 5*60+0,
currentTime:0,
remainingTime:null,
min:0,
sec:0,
startFlag:false,
resetFlag:false}
}
componentDidMount(){
this.interval=setInterval(this.inc,10000)
if(debug)console.log('COMPONENTDIDMOUNT',this.state)
}
static getDerivedStateFromProps(nextProps, prevState) {
if(debug)console.log('GETDERIVEDSTATEFROMPROPS',prevState)
return null
}
shouldComponentUpdate(nextProps,nextState){
if(debug)console.log('SHOULDCOMPONENTUPDATE',nextState)
return true
}
componentDidUpdate(){
if(debug)console.log('COMPONENTDIDUPDATE',this.state)
}
componentWillUnmount(){
if(debug)console.log('COMMPONENTWILLUNMOUNT',this.state)
}
startToggle(){
if(endTime === null)this.setState({remainingTime:this.state.workTime,
startFlag:!this.state.startToggle})
else this.setState({remainingTime:!this.state.startFlag})
}
textTime(){
let min = Math.floor(this.state.remainingTime / 60).toString()
let sec = (this.state.remainingTime % 60)
if (sec < 10)sec ? '0' + sec : sec.toString()
this.setState({min:min,sec:sec})
}
inc(){
console.log(this.state)
}
captureInput(){}
render() {
console.log('RENDER',this.state)
return (
<View style={styles.container}>
<Text style={styles.bigFont}>{`${this.state.timer + 'TIMER'}`}</Text>
<Text style={styles.bigFont}>12:00</Text>
<View style={styles.button}>
<Button title='START' onPress={()=>this.startToggle()} />
<Button title='RESET' onPress={()=>this.resetToggle()} />
</View>
<View style={styles.row}>
<Text style={[styles.bold,{marginRight:10},{width:112},
{textAlign:'right'}]}>
'Work Timer:'</Text>
<Text style={styles.bold}> min:</Text>
<TextInput
defaultValue='50'
style={styles.input}
onChangeText={(text) => {this.captureInput(text)}}
/>
<Text style={styles.bold}> sec:</Text>
<TextInput
defaultValue='50'
style={styles.input}
onChangeText={(text) => {this.captureInput(text)}}
/>
</View>
<View style={styles.row}>
<Text style={[styles.bold,{marginRight:10},{width:112},
{textAlign:'right'}]}>
'Break Timer:'</Text>
<Text style={styles.bold}> min:</Text>
<TextInput
defaultValue='50'
style={styles.input}
onChangeText={(text) => {this.captureInput(text)}}
/>
<Text style={styles.bold}> sec:</Text>
<TextInput
defaultValue='50'
style={styles.input}
onChangeText={(text) => {this.captureInput(text)}}
/>
</View>
</View>
)
}
}
You have 2 options:
Change inc() to inc = () =>
or
Change this.inc to this.inc.bind(this)
Change your inc method declaration to
inc = () => {
...
}
As per your code, this inside inc() is not referring to the component, hence you are not getting state either.
Hope this will help!

react native get TextInput value

I am stuck with a very simple problem. I have login form with username, password and button. In my button handler, I try to get the textinput value. But always get undefined value. Am I missing something?
render() {
<ExScreen
headerColor={this.state.headerColor}
scrollEnabled={this.state.enableScroll}
style={styles.container} >
<View >
<View >
<View style={[styles.inputContainer]} >
<TextInput
ref= "username"
onChangeText={(text) => this.setState({text})}
value={this.state.username}
/>
</View>
<Button style={{color: 'white', marginTop: 30, borderWidth: 1, borderColor: 'white', marginLeft: 20*vw, marginRight: 20*vw, height: 40, padding: 10}}
onPress={this._handlePress.bind(this)}>
Sign In
</Button>
...
_handlePress(event) {
var username=this.refs.username.value;
The quick and less optimized way to do this is by using arrow function inside your onChangeText callback, by passing username as your argument in your onChangeText callback.
<TextInput
ref= {(el) => { this.username = el; }}
onChangeText={(username) => this.setState({username})}
value={this.state.username}
/>
then in your _handlePress method
_handlePress(event) {
let username=this.state.username;
}
But this has several drawbacks!!!
On every render of this component a new arrow function is created.
If the child component is a PureComponent it will force re-renders unnecessarily, this causes huge performance issue especially when dealing with large lists, table, or component iterated over large numbers. More on this in React Docs
Best practice is to use a handler like handleInputChange and bind ```this`` in the constructor.
...
constructor(props) {
super(props);
this.handleChange= this.handleChange.bind(this);
}
...
handleChange(event = {}) {
const name = event.target && event.target.name;
const value = event.target && event.target.value;
this.setState([name]: value);
}
...
render() {
...
<TextInput
name="username"
onChangeText={this.handleChange}
value={this.state.username}
/>
...
}
...
Or if you are using es6 class property shorthand which autobinds this. But this has drawbacks, when it comes to testing and performance. Read More Here
...
handleChange= (event = {}) => {
const name = event.target && event.target.name;
const value = event.target && event.target.value;
this.setState([name]: value);
}
...
render() {
...
<TextInput
name="username"
onChangeText={this.handleChange}
value={this.state.username}
/>
...
}
...
You should use States to store the value of input fields.
https://facebook.github.io/react-native/docs/state.html
To update state values use setState
onChangeText={(value) => this.setState({username: value})}
and get input value like this
this.state.username
Sample code
export default class Login extends Component {
state = {
username: 'demo',
password: 'demo'
};
<Text style={Style.label}>User Name</Text>
<TextInput
style={Style.input}
placeholder="UserName"
onChangeText={(value) => this.setState({username: value})}
value={this.state.username}
/>
<Text style={Style.label}>Password</Text>
<TextInput
style={Style.input}
placeholder="Password"
onChangeText={(value) => this.setState({password: value})}
value={this.state.password}
/>
<Button
title="LOGIN"
onPress={() =>
{
if(this.state.username.localeCompare('demo')!=0){
ToastAndroid.show('Invalid UserName',ToastAndroid.SHORT);
return;
}
if(this.state.password.localeCompare('demo')!=0){
ToastAndroid.show('Invalid Password',ToastAndroid.SHORT);
return;
}
//Handle LOGIN
}
}
/>
In React Native 0.43: (Maybe later than 0.43 is OK.)
_handlePress(event) {
var username= this.refs.username._lastNativeText;
If you are like me and doesn't want to use or pollute state for one-off components here's what I did:
import React from "react";
import { Text, TextInput } from "react-native";
export default class Registration extends Component {
_register = () => {
const payload = {
firstName: this.firstName,
/* other values */
}
console.log(payload)
}
render() {
return (
<RegisterLayout>
<Text style={styles.welcome}>
Register
</Text>
<TextInput
placeholder="First Name"
onChangeText={(text) => this.firstName = text} />
{/*More components...*/}
<CustomButton
backgroundColor="steelblue"
handlePress={this._register}>
Submit
</CustomButton>
</RegisterLayout>
)
}
}
export default class App extends Component {
state = { username: '', password: '' }
onChangeText = (key, val) => {
this.setState({ [key]: val})
}
render() {
return (
<View style={styles.container}>
<Text>Login Form</Text>
<TextInput
placeholder='Username'
onChangeText={val => this.onChangeText('username', val)}
style={styles.input}
/>
<TextInput
placeholder='Password'
onChangeText={val => this.onChangeText('password', val)}
style={styles.input}
secureTextEntry={true}
/>
</View>
);
}
}
Hope this will solve your problem
This work for me
<Form>
<TextInput
style={{height: 40}}
placeholder="userName"
onChangeText={(text) => this.userName = text}
/>
<TextInput
style={{height: 40}}
placeholder="Password"
onChangeText={(text) => this.Password = text}
/>
<Button
title="Sign in!"
onPress={this._signInAsync}
/>
</Form>
and
_signInAsync = async () => {
console.log(this.userName)
console.log(this.Password)
};
Please take care on how to use setState(). The correct form is
this.setState({
Key: Value,
});
And so I would do it as follows:
onChangeText={(event) => this.setState({username:event.nativeEvent.text})}
...
var username=this.state.username;
Try Console log the object and you will find your entered text inside nativeEvent.text
example:
handelOnChange = (enteredText) => {
console.log(enteredText.nativeEvent.text)
}
render()
return (
<SafeAreaView>
<TextInput
onChange={this.handelOnChange}
>
</SafeAreaView>
)
constructor(props) {
super(props);
this.state ={
commentMsg: ''
}
}
onPress = () => {
alert("Hi " +this.state.commentMsg)
}
<View style={styles.sendCommentContainer}>
<TextInput
style={styles.textInput}
multiline={true}
onChangeText={(text) => this.setState({commentMsg: text})}
placeholder ='Comment'/>
<Button onPress={this.onPress}
title="OK!"
color="#841584"
/>
</TouchableOpacity>
</View>
Simply do it.
this.state={f_name:""};
textChangeHandler = async (key, val) => {
await this.setState({ [key]: val });
}
<Textfield onChangeText={val => this.textChangeHandler('f_name', val)}>
Every thing is OK for me by this procedure:
<Input onChangeText={this.inputOnChangeText} />
and also:
inputOnChangeText = (e) => {
this.setState({
username: e
})
}
React Native Latest -> Simple and easy solution using state based approach.
const [userEmail, setUserEmail] = useState("");
<TextInput
value={userEmail}
style={styles.textInputStyle}
placeholder="Email"
placeholderTextColor="steelblue"
onChangeText={(userEmail) => setUserEmail(userEmail)}
/>
If you set the text state, why not use that directly?
_handlePress(event) {
var username=this.state.text;
Of course the variable naming could be more descriptive than 'text' but your call.
There is huge difference between onChange and onTextChange prop of <TextInput />. Don't be like me and use onTextChange which returns string and don't use onChange which returns full objects.
I feel dumb for spending like 1 hour figuring out where is my value.
You dont need to make a new function for taht.
just make a new useState and use it in onchange.
const UselessTextInput = () => {
const [text, onChangeText] = React.useState("Useless Text");
const [number, onChangeNumber] = React.useState(null);
return (
<SafeAreaView>
<TextInput
style={styles.input}
onChangeText={onChangeText}
value={text}
/>
<TextInput
style={styles.input}
onChangeText={onChangeNumber}
value={number}
placeholder="useless placeholder"
keyboardType="numeric"
/>
</SafeAreaView>
);
};
This piece of code worked for me. What I was missing was I was not passing 'this' in button action:
onPress={this._handlePress.bind(this)}>
--------------
_handlePress(event) {
console.log('Pressed!');
var username = this.state.username;
var password = this.state.password;
console.log(username);
console.log(password);
}
render() {
return (
<View style={styles.container}>
<TextInput
ref="usr"
style={{height: 40, borderColor: 'gray', borderWidth: 1 , marginTop: 10 , padding : 10 , marginLeft : 5 , marginRight : 5 }}
placeHolder= "Enter username "
placeholderTextColor = '#a52a2a'
returnKeyType = {"next"}
autoFocus = {true}
autoCapitalize = "none"
autoCorrect = {false}
clearButtonMode = 'while-editing'
onChangeText={(text) => {
this.setState({username:text});
}}
onSubmitEditing={(event) => {
this.refs.psw.focus();
}}
/>
<TextInput
ref="psw"
style={{height: 40, borderColor: 'gray', borderWidth: 1 , marginTop: 10,marginLeft : 5 , marginRight : 5}}
placeholder= "Enter password"
placeholderTextColor = '#a52a2a'
autoCapitalize = "none"
autoCorrect = {false}
returnKeyType = {'done'}
secureTextEntry = {true}
clearButtonMode = 'while-editing'
onChangeText={(text) => {
this.setState({password:text});
}}
/>
<Button
style={{borderWidth: 1, borderColor: 'blue'}}
onPress={this._handlePress.bind(this)}>
Login
</Button>
</View>
);``
}
}
User in the init of class:
constructor() {
super()
this.state = {
email: ''
}
}
Then in some function:
handleSome = () => {
console.log(this.state.email)
};
And in the input:
<TextInput onChangeText={(email) => this.setState({email})}/>
Did you try
var username=this.state.username;