Reputation: 47
import React, { Component } from 'react';
import { Text, View, TextInput, Button, Alert } from 'react-native';
import datum from './data';
export default class Signup extends React.Component {
constructor(props) {
super(props);
this.state = { name: 'sff', number: '' };
}
signupPressed = () => {
const { name } = this.state;
console.log('checkss', name);
};
render() {
return (
<View
style={{
flex: 1,
flexDirection: 'column',
justifyContent: 'space-evenly',
alignItems: 'center',
}}>
<TextInput
style={{
height: 40,
borderColor: 'gray',
borderWidth: 1,
width: '50%',
}}
onChangeText={TextInputValue => this.setState({ name })}
placeholder="Name"
/>
<TextInput
style={{
height: 40,
borderColor: 'gray',
borderWidth: 1,
width: '50%',
}}
onChangeText={text => this.setState({ name })}
placeholder="Mobile no"
/>
<Button
onPress={this.signupPressed}
title="Signup"
color="#841584"
accessibilityLabel="Learn more about this purple button"
/>
</View>
);
}
}
I have Text input but the onChangeText props is not working as it is
Expected behavior Has to log the updated name value from the state when the button is clicked
Reality
when I click the button it logs me "checkss" only, not the name value
What is strange here!!
when I click the button for the first time it logs me "checkss,sff" but, when I click it for the second time it shows checkss only
Upvotes: 1
Views: 2012
Reputation: 51
Your code fails because you made a mistake when you declare de arrow function
onChangeText={TextInputValue => this.setState({name})}
It must be
onChangeText={TextInputValue => this.setState({ name: TextInputValue })}
Using Ecma6 can be simplified as
onChangeText={name => this.setState({ name })}
To avoid performance issues it is recommended not to use an inline function because is instantiated in all the render cycles. Is better if you create a class method and use it by reference.
export default class Signup extends React.Component {
constructor(props) {
super(props)
this.state = {name:"sff",number:""};
this.handleChange = this.handleChange.bind(this);
}
handleChange(name) {
this.setState({ name });
}
render() {
/* rest of code omitted */
<TextInput
style={
{ height: 40, borderColor: 'gray', borderWidth: 1,width:'50%' }
}
onChangeText={this.handleChange}
placeholder="Mobile no"
/>
/* rest of the code omitted */
}
}
Upvotes: 0
Reputation: 118
<TextInput
style={{height: 40, borderColor: 'gray', borderWidth: 1,width:'50%'}}
onChangeText={(text) => this.setState({name: text })}
placeholder="Name"
/>
Upvotes: 0
Reputation: 4961
That's because in onChangeText
you'll need to do this,
onChangeText={value=>{this.setState({stateVariable:value})}};
Upvotes: 1
Reputation: 1755
<TextInput
value={this.state.name}
style={{height: 40, borderColor: 'gray', borderWidth: 1,width:'50%'}}
onChangeText={(name) => this.setState({name})}
placeholder="Name"
/>
Try above code it will work for you
Upvotes: 0