Reputation: 531
I have had this issue for a while so i'm hoping to find an ansewer here. I tried to implement a simple select tag based on the code given in the react docs. However, this does not work for me. Here is the code that I have written:
<select value={this.state.formId} onChange={this.handleInternalFormChange}>
{
Object.keys(this.state.userForms).map(formKey => (
<option key={formKey} value={formKey} > {this.state.userForms[formKey]} </option>
))
}
and here is the function that calls onChange,
handleInternalFormChange = (e) =>{
this.setState({
formId: e.target.value
})
console.log(this.state.formId);
}
Upon having made these changes, the onChange function does not seem to work. i tried to print out the event that is called but it doesn't seem to contain a target
. Not sure what to do anymore, can someone help with this?
Upvotes: 2
Views: 69
Reputation: 1746
If you want to get console.log
result, check this
handleInternalFormChange = (e) =>{
this.setState({
formId: e.target.value
}, () => {
console.log(this.state.formId);
})
}
Upvotes: 1
Reputation: 4557
There is nothing wrong with the way you are currently doing it.
The reason your console.log()
is not printing out the state is because setState()
is asynchronous (console.log()
is also asynchronous by the way). If you would like to see what the updated state is, use setState()
's second parameter, which provides you with the new value.
You can confirm that the event is being used in onChnage()
by replacing your function call with:
<select onChange={e=>console.log(e.target.value)}>
If you want to check the value after your state is updated do:
this.setState({value}, updatedState=>console.log(updatedState));
Hope that helps clear things up,
Upvotes: 2