Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Counting vowels in a string with React hooks

I am unable to figure out how to print the number of vowels that I type into a form. I am not sure where the bug is, but when I submit the form, nothing happens.

const App = () => {
  const [results, setResults] = useState(0);
  const [input, setInput] = useState('');

  const handleSubmit = (e, input) => {
    e.preventDefault();

    let count = 0;
    for (let i = 0; i < input.length(); i++) {
      if (
        input.charAt(i) === 'a' ||
        input.charAt(i) === 'e' ||
        input.charAt(i) === 'i' ||
        input.charAt(i) === 'o' ||
        input.charAt(i) === 'u'
      ) {
        count++;
      }
    }
    setResults(count);
  };

  return (
    <div className="App">
      <div>{results}</div>
      <div>
        <form onSubmit={(e) => handleSubmit(e, input)}>
          <input
            type="text"
            value={input}
            onChange={(e) => setInput(e.target.value)}
          ></input>
          <button>Submit</button>
        </form>
      </div>
    </div>
  );
};

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

There was a mistake in the code. length is not a function. It’s just a property of input string.
It should be

input.length

instead of

input.length()

Code sandbox => https://codesandbox.io/s/clever-danny-sg819?file=/src/App.js

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading