I'm just getting started with ES6 and React and I want to create a validate method in my component class to validate before proceeding.
class LoginPage extends React.Component {
constructor(props) {
super(props);
this.setUser = this.setUser.bind(this);
this.isFormValid = this.isFormValid.bind(this);
this.state = {
user: {
username: '',
password: ''
}
};
}
isFormValid() {
console.log("is valid");
let isValid = true;
let errors = {};
if (this.state.user.username.length <= 0) {
errors.username = "Username cannot be blank";
isValid = false;
}
if (this.state.user.password.length <= 0) {
errors.password = "Password cannot be blank";
isValid = false;
}
this.setState({ errors: errors });
return isValid;
}
setUser(event) {
let username = event.target.username;
let password = event.target.password;
this.setState({
user: {
username: username,
password: password
},
errors: {}
});
}
loginUser(event) {
event.preventDefault();
if (!this.isFormValid()) {
return;
}
}
render() {
return (
<LoginForm
user={this.state.user}
onChange={this.setUser}
onLogin={this.loginUser} />
);
}
Is there something different about binding instance methods in a react component than event handlers? I have a setUser method that I pass to the child component that gets called correctly. But When I try to call isFormValid
from within loginUser eventHandler, I get
Uncaught TypeError: Cannot read property 'isFormValid' of null