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)

0

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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 });
}

Comments

2

I needed to add:

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

In the constructor!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.