React - Setstate On Input Field Not Working
Solution 1:
Because setState
is asynchronous. But fortunately there is a callback parameter in the method call which you can use to get the value like this
this.setState({
text: 'new state: ' + event.target.value
}, () => {
console.log(text)
})
Btw you are not assigning anything to setState
it's a method call.
Besides that since events
are synthetic events in React you have to store the current target in a variable to not lose the event for example like this
const saveValue = event.target.value;
this.setState({
text: 'new state: ' + saveValue
});
console.log(saveValue);
Solution 2:
Store the changed value, setState()
is asynchronous.
handleInputChange(event) {
const myValue = event.target.value;
this.setState({
text: myValue
})
}
Solution 3:
Why do you have 'new state: ' in the setState? The onChange function is called on every key press or change, so you shouldn't add your own text inside of the setState function. If you wanna use ES6, you can change the onChange call to:
(event) => this.handleInputChange(event.target.value)
and the handleInput function to:
handleInputChange(value) {
this.setState({
text: value
})
}
If you need the 'new state: ' string before the input text then put it inside of a span before the input instead.
Post a Comment for "React - Setstate On Input Field Not Working"