React Native call onChange on textinput when state change through network call - react-native

I have a dropdown list once change a network call is fire and getting some value from server now i would like to dynamicall change the input value but onchange is not firing once i am setting the state after network call.
Input screen with render
<SearchableDropdown style={styles.inputBox}
onTextChange={this.onChangeText}
selectedItems={this.state.selectedItems}
onItemSelect={(item) => {
const items = this.state.selectedItems;
this.setState({ serviceid: JSON.stringify(item.id) });
this.getServiceCategories(JSON.stringify(item.id))
this.setState({
CategoryName:this.state.CategoryName
});
}}
containerStyle={{ padding: 5 }}
textInputStyle={{
padding: 12,
borderWidth: 1,
borderColor: '#ccc',
borderRadius: 15,
color: '#000',
width:300
}}
itemStyle={{
padding: 10,
marginTop: 2,
backgroundColor: '#ddd',
borderColor: '#fff',
borderWidth: 1,
borderRadius: 15,
color: '#000',
}}
itemTextStyle={{ color: '#000' }}
itemsContainerStyle={{ maxHeight: 240 }}
items={this.state.serviceData}
defaultIndex={0}
placeholder="Select Service"
name="serviceid"
resetValue={false}
underlineColorAndroid="transparent"
/>
<Field style={styles.inputBox}
name="categoryid"
value={this.state.CategoryName}
placeholder="Category"
returnKeyLabel={this.state.CategoryID}
component={this.renderTextInput}
/>
<Field style={styles.inputBox}
name="subcategoryid"
value={this.state.SubCategoryName}
returnKeyLabel={this.state.SubCategoryID}
placeholder="Sub Category"
component={this.renderTextInput}
/>
Renderinput
renderTextInput = (field) => {
const {meta: {touched, error}, label, secureTextEntry, maxLength,value, keyboardType, placeholder, input: {onChange, ...restInput}} = field;
return (
<View>
<InputText
onChangeText={onChange}
maxLength={maxLength}
keyboardType={keyboardType}
secureTextEntry={secureTextEntry}
label={label}
{...restInput} />
{(touched && error) && <Text style={styles.errorText}>{error}</Text>}
</View>
);
}
}
input component
class InputText extends Component<{}> {
state = {
value: ""
}
componentDidMount() {
this.setState({
value: this.props.value
});
}
onChangeText = (value) => {
this.setState({
value
}, () => {
this.props.onChangeText(value);
})
}
render() {
const {placeholder, secureTextEntry, keyboardType, maxLength, onChangeText, onSubmitEditing,value} = this.props;
return (
<View>
<TextInput
style={styles.inputBox}
underlineColorAndroid="rgba(0,0,0,0)"
placeholder={placeholder}
placeholderTextColor="rgba(255,255,255,0.8)"
selectionColor="#999999"
secureTextEntry={secureTextEntry}
keyboardType={keyboardType}
maxLength={maxLength}
returnKeyType="next"
value={this.state.value}
onSubmitEditing={onSubmitEditing}
onChangeText={this.onChangeText} />
</View>
);
}
}
Once dropdown change network api call
getServiceCategories =(value)=>{
fetch('http://localhost/api/getServiceCategories?serviceid='+value)
.then(response => { return response.json();})
.then(responseJson => {
this.setState({
CategoryID:responseJson[0].CategoryID,
SubCategoryID:responseJson[0].SubCategoryID,
CategoryName:responseJson[0].CategoryName,
SubCategoryName:responseJson[0].SubCategoryName,
});
})
.catch(error => {
console.error(error);
});
}
thanks

The problem is in your InputText component. This component is keeping the value inside its own state and sets the text input value from its state, rather than using the value from the props.
You have two choices: remove the state from the component and use only the value from the props - in this way your component will be controlled by the parent:
class InputText extends Component<{}> {
render() {
const {placeholder, secureTextEntry, keyboardType, maxLength, onChangeText, onSubmitEditing,value} = this.props;
return (
<View>
<TextInput
style={styles.inputBox}
underlineColorAndroid="rgba(0,0,0,0)"
placeholder={placeholder}
placeholderTextColor="rgba(255,255,255,0.8)"
selectionColor="#999999"
secureTextEntry={secureTextEntry}
keyboardType={keyboardType}
maxLength={maxLength}
returnKeyType="next"
value={value} // Use `value` from props
onSubmitEditing={onSubmitEditing}
onChangeText={onChangeText} /> // Use `onChangeText` from props
</View>
);
}
}
Or keep the state, and pass the value from its props to the TextInput and keep the state value as a fallback, in the case when the prop value is not set.
class InputText extends Component<{}> {
state = {
value: ""
}
componentDidMount() {
this.setState({
value: this.props.value
});
}
onChangeText = (value) => {
this.setState({
value
}, () => {
this.props.onChangeText(value);
})
}
render() {
const {placeholder, secureTextEntry, keyboardType, maxLength, onChangeText, onSubmitEditing,value} = this.props;
return (
<View>
<TextInput
style={styles.inputBox}
underlineColorAndroid="rgba(0,0,0,0)"
placeholder={placeholder}
placeholderTextColor="rgba(255,255,255,0.8)"
selectionColor="#999999"
secureTextEntry={secureTextEntry}
keyboardType={keyboardType}
maxLength={maxLength}
returnKeyType="next"
value={value || this.state.value} // Note that now the value is the value from the props and if it will be falsey, then the state value will be used as a fallback.
onSubmitEditing={onSubmitEditing}
onChangeText={this.onChangeText} />
</View>
);
}
}

Related

initialState resets after dispatch actions in react useReducer

In my app, I fetch users data from the server inside the useEffect hook and set the initialState of the useReducer. When action dispatch happens on text input change, the initialState resets instead of updating thus I can't type a word inside the input. Can someone figure out the problem, please? I'm fairly new to react reducers. I have attached the relevant codes. Thanks.
EditProfile.js
const EditProfile = ({ navigation, route }) => {
const userid = route.params.userid;
const { user } = React.useContext(AuthContext);
const [userData, setUserData] = React.useState(null);
const initialState = {
name: userData ? (userData.name ? userData.name : "") : "",
dob: userData ? (userData.dob ? userData.dob.toDate() : "") : "",
phone: userData ? (userData.phone ? userData.phone : "") : "",
location: userData ? (userData.location ? userData.location : "") : "",
caption: userData ? (userData.caption ? userData.caption : "") : "",
};
React.useEffect(() => {
async function fetchData() {
const response = await getUserData(userid);
setUserData(response);
}
fetchData();
}, []);
const reducer = (state, action) => {
switch (action.type) {
case "nameInputChange":
return {
...state,
name: action.name,
};
case "dobInputChange":
return {
...state,
dob: action.dob,
};
case "phoneInputChange":
return {
...state,
phone: action.phone,
};
case "locationInputChange":
return {
...state,
location: action.location,
};
case "captionInputChange":
return {
...state,
caption: action.caption,
};
}
};
const [data, dispatch] = React.useReducer(reducer, initialState);
const nameInputChange = (value) => {
dispatch({
type: "nameInputChange",
name: value,
});
console.log("Name: ", initialState.name);
};
const dobInputChange = (date) => {
dispatch({
type: "dobInputChange",
dob: date,
});
};
const phoneInputChange = (value) => {
dispatch({
type: "phoneInputChange",
phone: value,
});
};
const locationInputChange = (value) => {
dispatch({
type: "locationInputChange",
location: value,
});
};
const captionInputChange = (value) => {
dispatch({
type: "captionInputChange",
caption: value,
});
};
return (
<View>
<FlatList
showsVerticalScrollIndicator={false}
ListHeaderComponent={() => (
<View>
<TouchableOpacity>
<Image
source={require("../assets/images/profile.jpg")}
style={{ width: "98%", height: "98%", borderRadius: 59 }}
/>
<View>
<Entypo name="camera" color="#8000e3" size={18} />
</View>
</TouchableOpacity>
<View>
<VerticalNameInput
type="name"
label="Full Name"
placeholder="Full name"
color="#9798ac"
placeholder="enter your full name"
onChangeText={(value) => nameInputChange(value)}
value={initialState.name}
/>
<VerticalDateInput
label="Date of Birth"
color="#9798ac"
dobInputChange={dobInputChange}
initialState={initialState}
/>
</View>
<View>
<VerticalNameInput
type="mobile"
label="Mobile"
color="#9798ac"
placeholder="mobile number"
onChangeText={(value) => phoneInputChange(value)}
value={initialState.phone}
/>
<VerticalNameInput
type="location"
label="Location"
color="#9798ac"
placeholder="city and country"
onChangeText={(value) => locationInputChange(value)}
value={initialState.location}
/>
</View>
<View>
<VerticalNameInput
type="caption"
label="Profile Caption"
color="#9798ac"
placeholder="enter about yourself"
onChangeText={(value) => captionInputChange(value)}
value={initialState.caption}
/>
</View>
</View>
)}
/>
<View style={{ position: "relative", top: -90, left: 200 }}>
<FloatingAction
onPressMain={() => {
updateUser(userid, userData);
}}
floatingIcon={<Entypo name="check" size={28} color="#fff" />}
/>
</View>
</View>
);
};
export default EditProfile;
VerticalNameInput.js
const VerticalNameInput = ({ label, color, placeholder, type, ...rest }) => {
return (
<View>
<Text>
{label}
</Text>
<View>
<View>
{type === "name" ? (
<AntDesign name="user" color="#000" size={15} />
) : type === "mobile" ? (
<AntDesign name="mobile1" color="#000" size={15} />
) : type === "location" ? (
<EvilIcons name="location" color="#000" size={20} />
) : type === "caption" ? (
<Ionicons
name="information-circle-outline"
color="#000"
size={18}
/>
) : null}
</View>
<TextInput
style={{ width: "85%", height: "100%" }}
numberOfLines={1}
placeholder={placeholder}
placeholderTextColor={color}
{...rest}
/>
</View>
</View>
);
};
export default VerticalNameInput;
VerticalDateInput.js
const VerticalDateInput = ({ label, color, dobInputChange, initialState }) => {
const [date, setDate] = React.useState(new Date());
const [open, setOpen] = React.useState(false);
return (
<View>
<Text>
{label}
</Text>
<View>
<View>
<AntDesign name="calendar" color="#000" size={15} />
</View>
<View>
<Text style={{ marginLeft: 10 }}>
{initialState.dob
? initialState.dob.toDateString()
: new Date().toDateString()}
</Text>
<TouchableOpacity
style={{ marginRight: 10 }}
onPress={() => setOpen(true)}
>
<AntDesign name="caretdown" color="#000" size={12} />
</TouchableOpacity>
</View>
<DatePicker
maximumDate={new Date()}
mode="date"
modal
open={open}
date={initialState.dob ? initialState.dob : date}
onConfirm={(date) => {
setOpen(false);
setDate(date);
dobInputChange(date);
}}
onCancel={() => {
setOpen(false);
}}
/>
</View>
</View>
);
};
export default VerticalDateInput;
Try add "default" case return current state in your reducer.
It might happen that you dispatch some unknown action, and reducer return undefined as a result.
const reducer = (state = initialState, action) => {
switch (action.type) {
default:
// If this reducer doesn't recognize the action type, or doesn't
// care about this specific action, return the existing state unchanged
return state
}
}

Change border color text input When its empty in react native

I want when text input is empty change border color to red with press button:
const post = () => {
let list = [];
if (homeAge === '') {
list.push('homeage')
}
}
<TextInput
style={[Styles.TextInput, { borderColor: list.includes('homeage') ? 'red' : '#006d41' }]}
onChangeText={(event) => homeAgeHandler(event)}
/>
<Button style={Styles.Button}
onPress={() => post()}>
<Text style={Styles.TextButton}>ثبت اطلاعات</Text>
</Button>
Use a useRef hook :
const ref=useRef(0);
const post = () => {
let list = [];
if (homeAge === '') {
list.push('homeage')
}
}
useEffect(()=>{
if(list.size==0&&ref.current)
{
ref.current.style.borderColor = "red";
}
},[list,ref]);
<TextInput ref={ref}
onChangeText={(event) => homeAgeHandler(event)}
/>
<Button style={Styles.Button}
onPress={() => post()}>
<Text style={Styles.TextButton}>ثبت اطلاعات</Text>
</Button>
Here is a simple example to validate text and change styling based on validation,
const App = () => {
const [text, setText] = useState("");
const [error, setError] = useState(false);
const validateText = () => {
if (text === "") {
setError(true);
} else {
setError(false);
}
};
return (
<View>
<TextInput style={[Styles.TextInput, { borderColor: error ? 'red' : '#006d41', borderWidth:'1px'}]}
onChangeText={setText}
/>
<Button style={Styles.Button}
onPress={validateText}>
<Text style={Styles.TextButton}>ثبت اطلاعات</Text>
</Button>
</View>
);
};
export default App;
TextInput empty:
TextInput not empty:
Use state instead.
Also, In the given example, you are trying to access the list which is the local variable of the post() method.
Here is the alternate solution:
export default function App() {
const [homeAge, setHomeAge] = useState('');
return (
<View style={styles.container}>
<TextInput
value={homeAge}
style={[
styles.textInput,
{ borderColor: !homeAge ? 'red' : '#006d41' },
]}
onChangeText={(text) => setHomeAge(text)}
/>
<Button title={'ثبت اطلاعات'} style={styles.button} onPress={() => {}} />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
},
textInput: {
padding: 10,
borderWidth: 1,
},
});
Working example: Expo Snack

Add text dynamically to TextInput

I would like to add a UnicodeText viewed inside the textInput when I click a button.
I've tried to create a state {text} then add the UnicodeText to the state text.
The text with the added text is properly shown in the console.log(). Not in the textInput.
import { Icon, Input } from "react-native-elements";
var emoji = require("node-emoji");
export default class MainViewMessageInput extends React.Component {
constructor(props) {
super(props);
this.state = {
text: "",
username: "",
visible: false,
showEmoticons: false
};
}
_sendMessage() {
var texte = this.state.text;
this.setState({ text: "" });
console.log(this.state.text);
}
_addEmoji() {
this.state.text = this.state.text + emoji.get("green_heart");
const emojiChar = this.state.text + emoji.get("green_heart");
this.setState({ text: emojiChar });
console.log(this.state.text);
}
render() {
return (
<View style={styles.container}>
<Input
style={{ flex: 1 }}
leftIcon={
<TouchableHighlight
onPress={() => {
this._addEmoji();
}}
style={styles.icon}
>
<Icon size={40} color="#d2d3d5" name="mood" />
</TouchableHighlight>
}
rightIcon={
<Icon
reverse
onPress={() => this.setState({ visible: true })}
color="#00b5ec"
name="send"
size={23}
/>
}
rightIconContainerStyle={{ marginRight: -7 }}
leftIconContainerStyle={{ marginLeft: 0 }}
inputContainerStyle={styles.inputContainer}
inputStyle={styles.input}
placeholder="Write your message ..."
underlineColorAndroid="transparent"
multiline={true}
editable={true}
onChangeText={text => this.setState({ text })}
/>
</View>
);
}
}
Is it possible to do?
you can push textinput into array in runtime so u get textinput dynamically
for input add field value={this.state.text}
reference
remove this.state.text = this.state.text + emoji.get("green_heart"); from _addEmoji()

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>
)
}
}

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;