NinetyHH NinetyHH - 3 months ago 32
React JSX Question

React-Native: Cannot set state from form values

I am trying to build a simple login form in React-Native using the tcomb-form-native component. I've created the method handleChange for setting the values to the initial state and the handleForm for submiting. Right now with my code when I'm typing something into the input fields the content is deleted and is replaced with the placeholder (no console output) and when I press the submit button im getting the error "undefined is not an object (evaluating this.refs.form)". Is there a better way how to do it?

Here is how I imported and set up everything:

import React, { Component } from 'react';

import {
Text,
View,
StyleSheet,
TextInput,
TouchableHighlight,
ActivityIndicator,
Image
} from 'react-native';

var t = require('tcomb-form-native');

var Form = t.form.Form;

var User = t.struct({
username: t.String,
password: t.String
});

var options = {
auto: 'placeholders',
fields: {
password: {
password: true
}
}
};


Here are my class and methods:

class Login extends Component {
constructor(props) {
super(props);
this.state = {
value: {
username: '',
password: ''
},
isLoading: false,
error: false
};
this.handleChange.bind(this);
}
handleChange(value) {
this.setState({value});
}
handleSubmit() {
var value = this.refs.form.getValue();
//update the indicator spinner
this.setState({
isLoading: true
});
console.log(value);
}


And this is how im rendering everything:

render() {
return (
<View style={styles.mainContainer}>
<View style={styles.logo}>
<Image source={require('../icon.png')} />
</View>
<Text style={styles.title}>Login</Text>
<Form
ref={(f) => this.form = f}
type={User}
options={options}
onChangeText={(value) => this.setState({value})}
value={this.state.value}
/>
<TouchableHighlight
style={styles.button}
onPress={this.handleSubmit}
underlayColor="white">
<Text style={styles.buttonText}>LOGIN</Text>
</TouchableHighlight>
</View>
);
}

Answer

Don't Use Bind When Passing Props

then you can do like this

onPress={this.handleSubmit}

handleSubmit = () => {...}