0

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
Crystal
  • 28,460
  • 62
  • 219
  • 393
  • You need to bind your component's this inside the constructor – Andrew Li Mar 07 '17 at 00:54
  • You have to do the same thing to `loginUser` that you are doing to `setUser` (i.e. bind it). `isFormValid` doesn't actually have to be bound. I recommend reviewing why binding is necessary so that you know what it actually does and when it is necessary. – Felix Kling Mar 07 '17 at 02:23

1 Answers1

2

The message Cannot read property 'isFormValid' of null says that isFormValid is being accessed from a null object. Meaning, this inside loginUser method is null. So bind the method that calls isFormValid in the constructor i.e loginUser.

constructor(props) {
  super(props);
  /// other methods
  this.loginUser = this.loginUser.bind(this);
}
Dhiraj
  • 33,140
  • 10
  • 61
  • 78