There is more than one issue with your code.
Use onChange, not onClick.
Since the event you are handling is a onClick
, it will never update until the second click.
<select value={this.state.value} onChange={this.handleNumber}>
Update the state properly.
In the code you provided, you are giving the select tag this value attribute: this.state.value
, which is fine if you use setState()
with the same property of the state.
You are using:
this.setState({
nb: newValue
});
This will update state.nb
, not state.value
. Use:
this.setState({
value: newValue
});
setState is asynchronous.
This means that React will decide when is the best moment to update the state, which might be later than when you want to use console.log()
.
Even if you use the onChange
event, you might not be able to read the state in the next line of code like this:
this.setState({
value: event.target.value
})
console.log(this.state.value)
The best approach to do something immediately after state changes, is the setState callback function:
this.setState({
value: event.target.value
},function(){
console.log(this.state.value)
})
And finally, your component with its respective corrections should look something like this:
class Example extends React.Component {
state = {
value: "0"
}
handleNumber = (event) => {
this.setState({
value: event.target.value
}, () => {
console.log(this.state.value)
})
}
render() {
return (
<div>
<p>choose Number</p>
<select value={this.state.value} onChange={this.handleNumber}>
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
<option value="four">4</option>
</select>
</div>
)
}
}
If you want to test it out, you can check this snippet.