Reputation: 359
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>
)
}
Upvotes: 0
Views: 529
Reputation: 1522
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);
}
Upvotes: 3
Reputation: 135
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
Upvotes: 0