Home > front end >  Counting vowels in a string with React hooks
Counting vowels in a string with React hooks

Time:12-30

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>
  );
};

CodePudding user response:

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

  • Related