Menu

Event Handling & Functions

Event Handling & Functions

Event handling in React allows components to respond to user actions such as clicks, typing, mouse movements, or form submissions. An event is something that happens in the app, and React lets you attach functions (called event handlers) to handle these events.

When an event occurs, the attached function runs automatically, letting the app respond immediately to the user’s action. This makes the interface interactive and dynamic.

const handleChange = (e) => {
    setInputValue(e.target.value);
};
const getCounts = (str) => {
    let charCount = str.length;
    let wordCount = 0;
    let inWord = false;
    for (let i = 0; i < str.length; i++) {
      const char = str[i];
      if (char !== " ") {
        if (!inWord) {
          wordCount++;
          inWord = true;
}
} else {
        inWord = false;
}
}
    return { charCount, wordCount };
};
const { charCount, wordCount } = getCounts(inputValue);

-------------------------

 <div className="counter-wrapper mt-6 w-full pt-3 pb-4 px-2 md:px-3">
          <h2 className="text-2xl md:text-3xl text-center">
Enter your input:
          </h2>
          <div className="input-container flex justify-center mt-4 relative w-[80%] mx-auto">
            <input
              type="text"
              name="text"
              id="text"
              className="mt-2 p-2 w-full text-lg md:text-xl"
              value={inputValue}
              onChange={handleChange}
            />
            {inputValue && (
              <FontAwesomeIcon
                icon={faCircleXmark}
                className="clear-icon text-xl md:text-2xl absolute cursor-pointer"
                onClick={() => setInputValue("")}
              />
)}
          </div>
          <div className="counter-section flex flex-col sm:flex-row gap-2.5 mt-4 text-xl md:text-2xl">
            <div className="counter w-1/2">
              <p>Character Count:</p>
              <p>{charCount}</p>
            </div>
            <div className="counter w-1/2">
              <p>Word Count:</p>
              <p>{wordCount}</p>
            </div>
          </div>
</div>

Explanation:

1. Event handling in this code occurs through the input field's onChange event. Whenever a user types anything in the input box, React automatically detects that change and triggers the handleChange function.

2. This function receives the event object (e), which contains details about what just happened in the input field.

3. From this event object, e.target.value returns the latest text entered by the user. That value is then passed to setInputValue, which updates the state.

4. As soon as the state updates, React re-renders the component, and the updated value appears in the input field and is used for further calculations, such as character and word count.

5. This is how the function processes the text to calculate character and word count:

  • The function getCounts(str) calculates both the character count and the word count from the given text. First, it stores the total number of characters using str.length, including spaces.
  • Then it sets wordCount to 0 and uses a flag, inWord, to track whether it is currently inside a word.
  • It then goes through each character one by one using a loop. If the character is not a space and it is not already inside a word, it increases the word count and marks inWord as true.
  • If a space is found, inWord is set to false, meaning the next non-space character will be counted as a new word. This way, it correctly counts words without counting extra spaces.
  • Finally, it returns both counts, which are then used to display the results.