Monday, June 3, 2024
142
rated 0 times [  148] [ 6]  / answers: 1 / hits: 19101  / 9 Years ago, mon, october 12, 2015, 12:00:00

I'm looking to make a react counter with target character count for a textarea just like Twitter's does, which reduces as the user types.



For example, on the Meta Description field, the target character count is 160. So, if the field is blank, the number would be 160. As the user types, the count is decreased with each character added to the input field until it reaches zero.



If the count is higher than the target, the numbers are written in red with a minus sign in front (again, just like twitter).



One way to do this is the listen to the onChange event on the textarea, and update the state of the component (which has the textarea and the counter), and then use that to calculate length and render the remaining char counter.



Is there a more efficient way?


More From » twitter-bootstrap

 Answers
37

Here is a rough version of what you wanted. Doesn't handle when chars_left goes below zero, but should be easy to implement.



var TwitterInput = React.createClass({
getInitialState: function() {
return {
chars_left: max_chars
};
},
handleChange(event) {
var input = event.target.value;
this.setState({
chars_left: max_chars - input.length
});
},
render: function() {
return (
<div>
<textarea onChange={this.handleChange.bind(this)}></textarea>
<p>Characters Left: {this.state.chars_left}</p>
</div>
);
}
});


https://jsfiddle.net/terda12/b0y4jL6t


[#64771] Thursday, October 8, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brandensebastiand

Total Points: 323
Total Questions: 115
Total Answers: 106

Location: China
Member since Mon, Aug 22, 2022
2 Years ago
;