1

I have the following code:

export default class Contact extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        password: '',
        redirect: false,
        username: ''
      };

  this.onUsernameChange = this.onUsernameChange.bind(this);
  this.onPasswordChange = this.onPasswordChange.bind(this);
}

onUsernameChange(event) {
  this.setState({ username: event.target.value });
}

onPasswordChange(event) {
  this.setState({ password: event.target.value });
}

handleSubmit(event) { 
  event.preventDefault();
  alert('A name was submitted: ' + this.state.username);

  //sessionStorage.setItem('username', this.state.username);

}

render() {

  return (
      <div>
        <form className="form-signin" onSubmit={this.handleSubmit}>
          <input type="text" value={this.username} onChange={this.onUsernameChange} />
          <input type="password" value={this.password} onChange={this.onPasswordChange} />
          <input type="submit" value="Submit" />
        </form>
      </div>
  );
}
}

After I submit the username and password: I get the following error:

TypeError: Cannot read property 'state' of undefined

On the following line:

alert('A name was submitted: ' + this.state.username);

What is the problem? Does the username not save? (I am using gatsby-reactjs)

bennygenel
  • 23,896
  • 6
  • 65
  • 78
Ron Arel
  • 371
  • 1
  • 5
  • 14

3 Answers3

5

You forgot to bind the handleSubmit as well

Do:

this.onUsernameChange = this.onUsernameChange.bind(this);
this.onPasswordChange = this.onPasswordChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);

in the constructor

Anand Undavia
  • 3,493
  • 5
  • 19
  • 33
5

You can also use the es6 format for functions which would prevent writing extra code for binding the this context everytime in the constructor. For example.

onUsernameChange = event => {
  this.setState({ username: event.target.value });
}
Anshul Bansal
  • 1,833
  • 1
  • 13
  • 12
2

I needed to add:

this.handleSubmit = this.handleSubmit.bind(this); 

In the constructor!

Ron Arel
  • 371
  • 1
  • 5
  • 14