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// */}
dumrich
  • 3
  • 1
  • 4

2 Answers2

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});
  }
Anuradha Kumari
  • 703
  • 5
  • 9
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);
}

OAH
  • 1,160
  • 2
  • 11
  • 24