Developing the Parent Application with Logic and UI
Developing the Parent Application with Logic and UI
This file defines the WordCounter component, which handles user input and displays character and word counts in real-time. It uses a state to store the input value, updates it through an event handler when the user types, processes the text using a function to calculate counts, and then renders the results along with a clear icon that appears only when input is present.
File Path: Word-Counter-Tool\src\components\WordCounter.jsx
import React from "react";
import { useState } from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faCircleXmark } from "@fortawesome/free-solid-svg-icons";
function WordCounter() {
const [inputValue, setInputValue] = useState("");
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);
return (
<>
<div className="counter-component flex flex-col items-center w-full md:w-[70%] lg:w-[50%] xl:w-[40%] py-5 px-2">
<div className="head-text text-center">
<h1 className="text-3xl md:text-4xl">Character & Word Counter</h1>
</div>
<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>{" "}
<p className="note mt-4 tex-base md:text-lg">
*Note: Every space you type is also counted as a character.
</p>
</div>
</>
);
}
export default WordCounter;









