-1

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;

```
  • Duplicate: [Why does calling react setState method not mutate the state immediately?](https://stackoverflow.com/questions/30782948/why-does-calling-react-setstate-method-not-mutate-the-state-immediately) –  Aug 01 '22 at 17:49
  • You're checking the previous value of `textarea`. –  Aug 01 '22 at 17:50
  • 1
    The first thing is your variable naming is too poor. Secondly setting useState hook's value is not synchronous. So after performing the `setTextarea` you are not guaranteed to get the `textarea` value. So, you should use `useEffect`. – Sajeeb Ahamed Aug 01 '22 at 17:50
  • Or simply store the length in a const and use that to call both setMessage and setTextarea (bad name choice though) –  Aug 01 '22 at 17:51

1 Answers1

1

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;
Meslzy
  • 104
  • 1
  • 9