Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
132
rated 0 times [  138] [ 6]  / answers: 1 / hits: 19522  / 7 Years ago, thu, may 4, 2017, 12:00:00

Im trying to implement a chartercter limit for a textArea in react js
here is my code.



state = {
chars_left: 140;
}

handleWordCount = event => {
const charCount = event.target.value.length;
const maxChar = this.state.chars_left;
const charLength = maxChar - charCount;
this.setState({ chars_left: charLength });
}

<textArea
rows={6}
type=text
maxLength=140
required
onChange={this.handleWordCount}
/>


{${this.state.chars_left}}



I have a function that should that show how many character the user is typing and it starts at 140 but it skips tons numbers every time i type something like 130 when i type a single character



what could the problem be?


More From » reactjs

 Answers
47

the problem is you are keep updating the chars_left attribute based on the old value



follow will work as expected



state = {
chars_left: 140;
}

handleWordCount = event => {
const charCount = event.target.value.length;
const charLeft = 140 - charCount;
this.setState({ chars_left: charLeft});
}


My example code can be improved by dynamically getting the maxlengt attr


[#57903] Tuesday, May 2, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
raymondorlandok

Total Points: 530
Total Questions: 110
Total Answers: 96

Location: Lebanon
Member since Wed, Dec 21, 2022
1 Year ago
;