'React js character limitation

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?



Solution 1:[1]

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

Solution 2:[2]

That was happening because everytime your were trying to subtract the number of characters that are there in textare from characters left. Define a new variable or state called max_char and get char_left by subtracting length from max_char. Also you dont need to write this.state.char_left in backticks since you are already using {}

class App extends React.Component {
    state = {
          chars_left: 140,
          max_char:140
        }

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

      return (
         <div>
          <textArea
            rows={6}
            type="text"
            maxLength="140"
            required
            onChange={this.handleWordCount}
          />
          <p>{this.state.chars_left}</p>
        </div>
     )
  }
}

ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>
<div id="app"></div>

Solution 3:[3]

This code helps you to be able to count the length of the character when entering text in the Textarea element. One of the advantages of this function is that it detects the user deleting characters or adding them.

Here you can use this code snippet:

  • Use the useState() hook to create the content state variable and set its value to that of value prop, trimmed down to limit characters.

  • Create a method setFormattedContent, which trims the content down to limit characters and memoize it, using the useCallback() hook.

  • Bind the onChange event of the to call setFormattedContent with the value of the fired event.

    const LimitedTextarea = ({ rows, cols, value, limit }) => {
    const [content, setContent] = React.useState(value.slice(0, limit));
    
    const setFormattedContent = React.useCallback(
      text => {
        setContent(text.slice(0, limit));
      },
      [limit, setContent]
    );
    
    return (
      <>
        <textarea
          rows={rows}
          cols={cols}
          onChange={event => setFormattedContent(event.target.value)}
          value={content}
        />
        <p>
          {content.length}/{limit}
        </p>
      </>
    );
    

    }; Examples ReactDOM.render( , document.getElementById('root') );

Solution 4:[4]

If you want to show certain amount of characters use the following code.

 {`${textToShow.substring(0, 70)}... `} 

Here instead of "textToShow" you can use your own text that you want to slice.

Solution 5:[5]

The problem is that you are basically using one variable to keep track of both the max number of characters, but also for how many chars remain.

I would also change maxLength in your textArea to use the state variable, instead of hard-coding it.

Try using two variables for this, like in the example below:

class MyApp extends React.Component {
  constructor() {
    super();
    this.state = {chars_left: 140, max_chars: 140};
  }
  
  handleWordCount = event => {
    const charCount = event.target.value.length;
    const maxChar = this.state.max_chars;
    const charLength = maxChar - charCount;
    this.setState({chars_left: charLength});
  }
  
  render() {
    return (
      <div>
        <textArea
          rows={6}
          type="text"
          maxLength={this.state.max_chars}
          required
          onChange={this.handleWordCount}
        />
        <div>{this.state.chars_left}</div>
      </div>
    );
  }
};

ReactDOM.render(<MyApp />, document.getElementById('myapp'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="myapp"></div>

Though, I would make another small change:

this.state = {chars_left: null, max_chars: 140};
...
<div>{this.state.chars_left || this.state.max_chars}</div>

This way chars_left doesn't need to know what max_chars is set to, and you have 1 less variable to manage should the limit change in the future.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Benjaco
Solution 2 Shubham Khatri
Solution 3 fatemeh kazemi
Solution 4 Dr Strange
Solution 5