1

I'm trying to create a counter that calculates the remaining characters but I cannot. I want to set the allowed characters to 100 and then subtract the number of characters written by the user from the 100, I wrote this


    class TextArea extends Component
    {

        state =
        {

            chars: 0,

        }

        charsRemaining()
        {

            var myTextArea = document.querySelector("textarea").value.length;


            this.setState({chars: this.state.chars - myTextArea});

            return myTextArea;
        }

        render()
        { 

            return (

                <div>

                    <textarea onKeyDown={this.charsRemaining()} cols="60" rows="10"></textarea>

                    <span>{this.state.chars}</span>

                </div>

            );

        };

    };

I thought if I set a variable to document.querySelector("textarea").value.length that would work. But it seems that I cannot access elements DOM this way in ReactJS. Any suggestions?

K. M.
  • 107
  • 7

2 Answers2

0

You don't have to calculate the remaining characters. With the implementation you are using with a plain textarea tag you can just use the maxlength attribute to specify the maximum number of characters allowed, like so:

<textarea maxLength="100" cols="60" rows="10"></textarea>
0

One of the problems may be that you are executing the function by putting () at the end. So instead of setting the value to a function, you are setting the value to the function's results.

So instead of this:

onKeyDown={this.charsRemaining()}

Try this:

onKeyDown={this.charsRemaining}

Another thing you might try is using the synthetic event passed to the function to get the value length.

charsRemaining( e ) {
    var myTextAreaLength = e.target.value.length;
    this.setState({chars: this.state.chars - myTextAreaLength});
}

I think there are other problems with the way you are constructing your component for React. You may want to find a tutorial of a working react component, and how they set the initial state, and bind functions to events. Or perhaps look at the answer to this question: How to get input textfield values when enter key is pressed in react js?

dqhendricks
  • 19,030
  • 11
  • 50
  • 83