Reputation: 108
I am trying to input email value from user and store it in a state variable. I have tried the following code but getting an error:
<Form.Control type="email" required placeholder="Enter email" value={this.state.email} onChange={this.setEmail}></Form.Control>
State variable is defined as follow:
this.state = {
email: '',
}
Following is my code to set the value entered by user in email:
setEmail = (e) => {
this.setState(() => ({email: e.target.value}))
}
I tried printing e.target.value. It is correct. But while running this code, I am getting error:
Cannot read property 'value' of null
Any comments on how to fix this issue?
Upvotes: 1
Views: 57
Reputation: 196276
That is happening because the event is not persisted, and it is used in an asynchronous function (setState
is async).
Just extract it before calling setState
.
setEmail = (e) => {
const {value} = e.target;
this.setState(() => ({email: value}))
}
Upvotes: 1