Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting characters from TextArea in ReactJs

I have something that I am trying to implement in react, its a simple functionality that calculates how many characters have been typed in to a textarea.

here goes the source code

var WordCount = React.createClass({

getInitialState: function() {
    return{ contacts: [], fullName: "What Ever", smsBalance: 0, command: 'Send Now', charsPerPage: 160, pageCount:0 };
},

wordCount: function(e){

    var currentText = e.target.value;
    //Now we need to recalculate the number of characters that have been typed in so far
    var characterCount = currentText.length;
    var charsPerPageCount = this.state.charsPerPage;
    var unitCount = Math.round(characterCount/charsPerPageCount);
    this.setState({pageCount: unitCount});
},

render: function() {
    return(
        <div className="md-card">


        <div className="user_content">
            <ul className="uk-margin">
                <div className="uk-margin-top">

                    <div className="uk-grid" data-uk-grid-margin="">
                        <div className="uk-width-medium-1-1">
                            <div className="md-input-wrapper">
                            <label htmlFor="Message">And Now Your Message</label>
                            <textarea className="md-input autosize_init" cols="30"
                                      data-val="true"
                                      data-val-required="The Message field is required."
                                      id="Message" ref="Message"
                                      rows="3" onChange={this.wordcount} style={{overflowX: "hidden", wordWrap: "break-word", height: 97+"PX"}}></textarea>
                            <span className="md-input-bar"></span></div>
                            <br/>
                            <span className="md-color-grey-300">
                                Current cost {this.state.pageCount}
                            </span>
                        </div>
                    </div>



                </div>
            </ul>
        </div>
        </div>
    );
}
});

ReactDOM.render(<WordCount/>, document.getElementById("PageContent"))

Ideally what i intend to achieve is count the number of characters that the user has entered so far in the text area and divide that number by some preset value to get the number of pages and display the number of pages for the users entry to the user

However, the sate variable 'pageCount' remains at zero perpetually. Please What am I doing wrong

Regards Peter

like image 681
Seth IK Avatar asked Nov 15 '25 11:11

Seth IK


1 Answers

A silly mistake, change onChange={this.wordcount} to onChange={this.wordCount}.

like image 122
Vikramaditya Avatar answered Nov 18 '25 20:11

Vikramaditya



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!