Please take a look at this simple fiddle.
It is a single react component, which is a textarea. It displays a counter below the textarea.
The goal is to have the counter update onChange
to reflect the new value (total text area length).
Unfortunately, my counter dissappears whenever a change happens. I suspect my this
or syntax is off specifically in the middle of this code block:
recalculate() {
this.setState({
text: this.state.text.length
});
}
But React is a new beast and so is ES6. What am I missing here?
You should set state
with new value, because now you always set default state
value
recalculate(e) {
this.setState({
text: e.target.value
});
}
Example
Your problem is you rely on this.state.text to populate your textarea. Once you type and call recalculate() you change this.state.text to an int and then try and call .length on this int and this causes the value to be undefined. I would recommend this: https://jsfiddle.net/74jufckm/1/
recalculate( event ) {
this.setState({
text: event.target.value,
textLength: event.target.value.length
});
}
You were also never setting the state of the text again when recalculating.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With