Home > front end >  Character counter
Character counter

Time:08-02

I'm creating a character counter with reactjs that shows the message while typing a text:

typing: counting

exact 10 characters: congratulations

exceeded the number of 10 characters: the count is not behaving as expected.

Any problem with the logic?

the code:

import React, {useState} from 'react'

function Form() {

    const [textarea, setTextarea] = useState(0);

    const [message, setMessage] = useState('counting');
    
    let total = 10;

    const handleTextarea = (e) => {

        setTextarea(e.target.value.length)

        if(textarea > total){

            setMessage('exceeded the limit');

        } else if(textarea == total) {

            setMessage('congratulations');
        
        } else {

            setMessage('counting');

        }
    }   

    return(
        <div id="container">
            <textarea
                name="textarea"
                onChange={handleTextarea}
            />

            <h3 id="message">{message} {textarea} / 10 character</h3>
        </div>
    )
}

export default Form;

```

CodePudding user response:

Do This

import React, {useState} from 'react'

function Form() {

  const [textarea, setTextarea] = useState("");

  const [message, setMessage] = useState('counting');

  let total = 10;

  const handleTextarea = (e) => {
    const value = e.target.value;
    const length = value.length;

    setTextarea(value);

    if (length > total) {
      setMessage('exceeded the limit');
    } else if (length == total) {
      setMessage('congratulations');
    } else {
      setMessage('counting');
    }
  }

  return (
    <div id="container">
            <textarea
              name="textarea"
              value={textarea}
              onChange={handleTextarea}
            />

      <h3 id="message">{message} {textarea.length} / 10 character</h3>
    </div>
  )
}

export default Form;
  • Related