0

I'm trying to get the values ​​from the input in the button click but when I click the error appears: Cannot read property 'state' of undefined.

This my code, in authentication function this.state returns: Cannot read property 'state' of undefined.

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

handleChange (event) {
  this.setState({
    [event.target.name]: event.target.value
  })
}

authentication() {
 console.log(this.state);
}

render() {
        return (
            <Fragment>
                <LoginStyles />
                <main>
                    <section>
                        <h2 className="title">Login</h2>

                        <div className="form__login">
                            <label>Nome:</label>
                            <input type="text" name="email" onChange={event => this.handleChange(event)} />

                            <label>Senha:</label>
                            <input type="password" name="pass" onChange={event => this.handleChange(event)} />

                            <button className="btn-default" onClick={this.authentication}>Acessar</button>
                        </div>
                    </section>
                </main>
            </Fragment> 
        )
    }
Gustavo Chagas
  • 344
  • 1
  • 13

2 Answers2

3

You should bind your authentication function as well as handleChange function. To do that you can either use bind method in constructor or use ES6 arrow operator as below-

handleChange = (event) => {
  this.setState({
    [event.target.name]: event.target.value
  })
}

authentication = () => {
 console.log(this.state);
}
techie_questie
  • 1,434
  • 4
  • 29
  • 53
0

As someone already mentioned, you have to bind the method in the constructor or in the onClick as he did

Here is a link to Handling Events in React

twcardenas
  • 115
  • 2
  • 10