kAy_4337270 kAy_4337270 - 11 days ago 6
Javascript Question

Get TextInput Value and Checkbox state in React native

I want to retirve the input value of username & password and the checkbox status. I have found this related question on Stackoverflow. But when try to implement this got error


'null' is not an object (evaluating
'this.state.username')


Can anyone help me to retrive input value and checkbox state as i am new to React-native

Code:

var CheckBox = require('react-native-checkbox');
var Button = require('react-native-button');

var reactnative = React.createClass({

render: function() {
return (
<View style={styles.container}>

<Text style={styles.signin}>Sign In</Text>

<TextInput style={styles.logininput} ref= "username" onChangeText={(event) => this.setState({username:event.nativeEvent.text})} value={this.state.username}/>

<TextInput style={styles.logininput} value="Password"/>

<CheckBox label='Remeber Me' checked = {false} onClick={this._CheckBoxState}/>

<Button style={styles.loginButton} onPress={this._handlePress.bind(this)}>
Login
</Button>

</View>
);
},

_handlePress(event) {
//Get TextInput value
var username= this.state.username;
alert(username);
},

_CheckBoxState(event){
//want to change the state from true to false or vice-versa

}
});

Answer

You may have missed to initialize an initial state function before rendering.

 ...
 getInitialState: function() {
    return {username: ''};
 },
 render: function() {
  ....
 }

Now this.state.username should be accessable.