0

I am trying to upload my react forms to the state so I can fetch an API with those credentials

I have tried creating a function that looks like this:

handleEmail(event) {
    this.setState({email: event.target.value});
  }
  handlePassword(event) {
    this.setState({password: event.target.value});
  }
  render() {
    return (
      <div>
        <NavBar />
        <form className="pt-6 container">
          <div className="form-group">
            <label className="mt-6" >Your email</label>
            <input name className="form-control" onChange={this.handleEmail} placeholder="Email" type="email" />
          </div> {/* form-group// */}
          <div className="form-group">
            <a className="float-right" href="#">Forgot?</a>
            <label>Your password</label>
            <input className="form-control" onChange={this.handlePassword} placeholder="******" type="password" />
          </div> {/* form-group// */}
1
  • 2
    There are so many questions about this being undefined; you need to bind it or use arrow functions. Commented May 18, 2019 at 14:18

2 Answers 2

1

This is a scoping issue. Since these methods are being called after event triggers, the this points to scope from which it is called, rather than pointing to the class instance where it is defined.
You need to use arrow functions to fix this.

handleEmail = (event) => {
    this.setState({email: event.target.value});
  }
  handlePassword = (event) => {
    this.setState({password: event.target.value});
  }
Sign up to request clarification or add additional context in comments.

Comments

0

You need to bind your function, add the constructor like this:

constructor(props) {
    super(props);
    this.state = {
        email: '',
        password:''
    };

    this.handleEmail= this.handleEmail.bind(this);
    this.handlePassword= this.handlePassword.bind(this);
}

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.