Character Counter App in React JS and Tailwind CSS

0

Hey everyone Let’s talk about how to make a character counter app in React JS and Tailwind CSS. It’s a simple but useful project for beginners. If you are new in React to build the project It’s the best choice for you. In the digital age, character counters are important units for lots of capabilities, from social media systems to content material management programs.

Character Counter App in React JS and Tailwind CSS

They assist clients in maintaining observation of the style of characters they’ve typed, making certain their input stays internal specific limits. In case you’re looking to create a clean but green character counter app, React JS and Tailwind CSS are incredible applied sciences to utilize.

React offers a strong framework for building dynamic individual interfaces, while Tailwind CSS offers a software-first approach to styling, making it sincere to create visually exciting designs. In this article, we’ll stroll you through the method of constructing a personality counter app utilizing these instruments.

Character Counter App in React JS and Tailwind CSS

Before moving the codes, you should watch the video tutorial that I made. The video is helpful for you to understand each thing that is used to build the project. If you face any problems during the video, you can check it the codes that I mentioned below.

I hope you’ve seen the video tutorial and you’ve learned something new from this tutorial. Let’s see the codes below.

Understanding the Fundamentals

Prior to diving into the event course, it’s vital to know the core performance of a personality counter app. The app ought to permit customers to enter textual content right into a textual content space or enter discipline and dynamically show the variety of characters they’ve typed. Moreover, it might embody options like setting a personality restriction and offering visible suggestions when the restriction is exceeded.

Setting Up Your Improvement Setting

To get began, you’ll have to arrange a React mission. You should utilize instruments like Create React App or Vite to rapidly scaffold a brand-new mission. As soon as your mission is ready, you’ll want to put in Tailwind CSS. Tailwind’s utility lessons will make it easier to type your app without writing customized CSS, saving you effort and time.

You May Also Like:

When you build a react project using vite, then you need to reset the complete codes which are default. Once you did that then you need to use below mentioned codes inside the App.jsx.

import React, { useState } from "react";
import LogoDark from "./assets/images/logo-dark-theme.svg";
import LogoLight from "./assets/images/logo-light-theme.svg";

import Sun from "./assets/images/icon-sun.svg";
import Moon from "./assets/images/icon-moon.svg";
import LetterCounter from "./assets/component/LetterCounter";

function App() {
  const [isDarkMode, setIsDarkMode] = useState(true);

  const ToggleDarkMode = () => {
    setIsDarkMode(!isDarkMode);
  };

  return (
    <div
      className={`${
        isDarkMode
          ? "bg-darkBlack text-WhiteColor"
          : "bg-WhiteColor text-darkBlack"
      } h-screen overflow-y-auto`}
    >
      <div className="container mx-auto px-4">
        <div className="flex justify-between py-8">
          <img src={isDarkMode ? LogoDark : LogoLight} alt="" />
          <img
            src={isDarkMode ? Sun : Moon}
            alt=""
            onClick={ToggleDarkMode}
            className={`${
              isDarkMode ? "bg-darkBlack" : "bg-Sliver"
            } p-2 rounded cursor-pointer`}
          />
        </div>
        <LetterCounter isDarkMode={isDarkMode} />
      </div>
    </div>
  );
}

export default App;

The next thing you need to build <LetterCounter/> a component. So, Let’s look at the codes that are used to implement the letter counter logic.

import React, { useState } from "react";
import Counter from "./Counter";
import CharacterImg from "../images/pattern-character-count.svg";
import WordCounterImg from "../images/pattern-word-count.svg";
import SentenceCounterImg from "../images/pattern-sentence-count.svg";
import LetterDensity from "./LetterDensity";

function LetterCounter({ isDarkMode }) {
  const [text, setText] = useState("");
  const [excludeSpace, setExcludeSpaces] = useState(false);
  const [limit, setLimit] = useState(null);
  const [ShowAllLetters, setShowAllLetters] = useState(false);

  //   Funcation to process the text based on exlude space and limit
  const processedText = () => {
    let currentText = text;
    if (excludeSpace) currentText = currentText.replace(/\s/g, "");
    if (limit) currentText = currentText.slice(0, limit);
    return currentText;
  };

  // Calculate character count
  const charCount = () => processedText().length;

  //   Calculate Word
  const wordCount = () => {
    const words = processedText()
      .split(/\s+/)
      .filter((word) => word !== "");
    return words.length;
  };

  //calculate sentense
  const sentencesCount = () => {
    const sentences = processedText()
      .split(/[.?!]/)
      .filter((s) => s !== "");
    return sentences.length;
  };

  // Calculte Letter Density
  const letterDensity = () => {
    const counts = {};
    const processed = processedText().toUpperCase();

    for (const char of processed) {
      if (/[A-Z]/.test(char)) counts[char] = (counts[char] || 0) + 1;
    }

    const total = Object.values(counts).reduce((sum, c) => sum + c, 0);
    return Object.entries(counts).map(([letter, count]) => ({
      letter,
      count,
      percentage: total > 0 ? ((count / total) * 100).toFixed(2) : 0,
    }));
  };

  const displayLetters = () => {
    const density = letterDensity();
    if (density.length > 5 && !ShowAllLetters) {
      return density.slice(0, 5);
    }
    return density;
  };

  return (
    <div>
      <h1 className="text-4xl font-bold text-center my-8">
        Analyze Your text in Real Time
      </h1>
      <textarea
        className={`${
          isDarkMode
            ? "text-WhiteColor bg-DarkGray"
            : "text-darkBlack bg-Sliver"
        } w-full h-48 p-2 border rounded-md resize-none focus:outline-none `}
        placeholder="Analyze your text in Real Time"
        value={text}
        onChange={(e) => setText(e.target.value)}
      />

      {/* Option and Read Time */}
      <div className="mt-4 flex items-center justify-between">
        <label className="inline-flex items-center">
          <input
            type="checkbox"
            className="form-checkbox mr-2"
            onChange={(e) => setExcludeSpaces(e.target.checked)}
          />
          <span>Exclude Spaces</span>
        </label>
        <label htmlFor="limit">
          <span className="mr-2">Set Character Limit</span>
          <input
            type="number"
            className={`${
              isDarkMode
                ? "bg-lightBlack text-WhiteColor"
                : "bg-Sliver text-darkBlack"
            } border rounded-md px-2 py-1 w-20 focus:outline-none`}
            onChange={(e) => {
              const num = parseInt(e.target.value, 10);
              setLimit(isNaN(num) ? null : num);
            }}
            value={limit === null ? null : limit}
            placeholder="Limit"
          />
        </label>
        <div>Appox. Read time; &lt; 1 minute</div>
      </div>

      {/* Counters  */}
      <div className="my-8 grid grid-cols-1 md:grid-cols-3 gap-4 text-darkBlack">
        <div className="bg-purpleColor rounded shadow-md flex justify-between">
          <Counter title="Total Characters" value={charCount()} />
          <img src={CharacterImg} alt="" />
        </div>
        <div className="bg-yellowColor rounded shadow-md flex justify-between">
          <Counter title="Word Counts" value={wordCount()} />
          <img src={WordCounterImg} alt="" />
        </div>
        <div className="bg-OrangeColor rounded shadow-md flex justify-between">
          <Counter title="Sentence Count" value={sentencesCount()} />
          <img src={SentenceCounterImg} alt="" />
        </div>
      </div>

      <LetterDensity
        letterDensity={letterDensity}
        displayLetters={displayLetters}
        ShowAllLetters={ShowAllLetters}
        setShowAllLetters={setShowAllLetters}
      />
    </div>
  );
}

export default LetterCounter;

We are almost done building a character counter app in React JS and tailwind CSS. We need to build the last component such as <LetterDensity/> Let’s look at the codes. and <Counter />.

Let’s look at the <Counter /> component code.

import React from "react";

function Counter({ title, value }) {
  return (
    <div className="px-4 py-8">
      <p className="text-6xl font-semibold">{value}</p>
      <p className="text-lg font-semibold">{title}</p>
    </div>
  );
}

export default Counter;

After that, we need to the <LetterDensity/> Code below.

import React from "react";

function LetterDensity({
  letterDensity,
  displayLetters,
  ShowAllLetters,
  setShowAllLetters,
}) {
  return (
    <div className="mt-4 rounded-md p-4">
      <p>Letter Density</p>
      {letterDensity().length > 0 ? (
        <div className="mt-2 overflow-x-auto">
          {displayLetters().map(({ letter, count, percentage }) => (
            <div className="flex items-center p-2 rounded-md my-1" key={letter}>
              <span className="font-bold">{letter}</span>
              <div className="ml-2 rounded-md w-full bg-Sliver h-4">
                <div
                  className={`rounded-md h-full ${
                    letterDensity().length > 0 ? "bg-purpleColor" : "bg-Sliver"
                  }`}
                  style={{ width: `${percentage}%` }}
                ></div>
              </div>
              <span className="ml-2 flex items-center gap-4">
                <div>{count}</div>
                <div>({percentage}%)</div>
              </span>
            </div>
          ))}
        </div>
      ) : (
        <p>No Character Found. Start Typing to See letter Density</p>
      )}
      {letterDensity().length > 5 && (
        <button onClick={() => setShowAllLetters(!ShowAllLetters)}>
          {ShowAllLetters ? " See Less" : "See More"}
        </button>
      )}
    </div>
  );
}

export default LetterDensity;

Designing the Consumer Interface

The person interface to your character counter app must be easy and intuitive. Begin by making a textual content space the place where customers can enter their textual content. Beneath the textual content space, show the character depend in real-time. You may also add a visible indicator, akin to a progress bar or color-changing textual content, to indicate how to shut the person to reach the character restriction.

Tailwind CSS makes it straightforward to type these parts. For instance, you should utilize Tailwind’s spacing utilities to place the textual content space and character depend show, and its coloration utilities to vary the textual content coloration based mostly on the character depend.

Implementing the Character Counting Logic

The core performance of your app lies within the character counting logic. Because the person varieties into the textual content space, the app ought to repeatedly replace the character depend. This may be achieved through the use of React’s state administration. You’ll have to create a state variable to carry the entered textual content and one other to retail the character depend.

Each time the person varieties, the app ought to replace the state with the brand new enter and calculate the character depend. This may be finished by utilizing the onChange occasion handler in React. The character depends can then be displayed beneath the textual content space, updating in real-time because of the person varieties.

Including a Character Restrict

To make your app extra helpful, you’ll be able to add a personality restriction characteristic. This permits customers to set the most variety of characters they’ll enter. When the person approaches or exceeds the restriction, the app can present visible suggestions, akin to altering the textual content coloration to purple or displaying a warning message.

You’ll be able to implement this characteristic by evaluating the present character depending on the predefined restriction. If the depend exceeds the restriction, you’ll be able to replace the UI to mirror this, utilizing Tailwind CSS to use the suitable types.

Enhancing the Consumer Expertise

To make your character counter app extra user-friendly, think about including further options. For instance, you possibly can embody a button to clear the textual content space, or a toggle to change between counting characters and phrases. You could possibly additionally add animations or transitions to make the app extra participating.

Tailwind CSS offers quite a lot of utilities including animations and transitions, making it straightforward to reinforce the person’s expertise without writing customized CSS.

Testing and Debugging

As soon as your app is constructed, it’s vital to check it completely to make sure it really works as anticipated. Take a look at the app by getting into completely different quantities of textual content and verifying that the character depends on updates appropriately. Verify that the character restrict characteristic works as meant and that the UI offers clear suggestions when the restriction is exceeded.

In case you encounter any points, use React’s developer instruments and browser console to debug the issue. Tailwind CSS additionally offers a useful set of debugging instruments that may make it easier to determine and repair styling points.

Deploying Your App

After testing and debugging, your character counter app is able to be deployed. You’ll be able to host it on platforms like Vercel, Netlify, or GitHub Pages, which provide straightforward deployment choices for React apps. As soon as deployed, share your app with others and collect suggestions to additional enhance it.

Conclusion

building a personality counter app in React JS and Tailwind CSS is a good way to observe your abilities in front-end improvement. By following the steps outlined in this article, you’ll be able to create a purposeful and visually interesting app that helps customers maintain observation of their character.

Whether or not you’re constructing this app for private use or as half of a bigger mission, the mixture of React and Tailwind CSS offers a robust and environment-friendly approach to delivering your concepts to life.

Previous articleHow to Make a Budget App in React JS
Asif Ali
"Hi, I'm Asif Ali, a developer with a passion for creating cool stuff with code. I've got a lot of experience making software that works well and solves problems. From coming up with ideas to actually building and testing them, I love every part of the process. I pay close attention to detail to make sure everything works smoothly. I enjoy working with different programming languages and collaborating with teams to turn ideas into real projects. I'm always learning and keeping up with the latest tech trends. My goal is to create useful and effective solutions that make a difference."

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.