Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - ES6 - Dynamically watching the total character length of a textarea

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?

like image 379
ilrein Avatar asked Oct 15 '25 14:10

ilrein


2 Answers

You should set state with new value, because now you always set default state value

recalculate(e) {
  this.setState({
     text: e.target.value
  });
}

Example

like image 190
Oleksandr T. Avatar answered Oct 18 '25 08:10

Oleksandr T.


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.

like image 35
Mike D Avatar answered Oct 18 '25 08:10

Mike D



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!