Add Calculation to the Character Counter Application

The last part of the application is to add the methods to calculate the number of characters and words to the display. To do that, you do not need to create a separate file. We can achieve the calculation by using useState(), strip(), trim() and length() functions we saw in the previous module.

  • Add the logic to the character counter component.
// CharacterCounter.jsx



// Import the function from the react package

import React, { useState } from "react";

import "./CharacterCounter.css";



function CharacterCounter() {

  // UseState() function is define the variables to handle the dynamic input

  const [text, setText] = useState("");

  

  // handleChange() function to get the text from textarea

  const handleChange = (e) => {

    setText(e.target.value);

  };



  // Calculate character count (including space as a character)

  const characterCount = text.length;



  // Calculate character count (excluding space as a character)

  const characterCountWithoutSpaces = text.replace(/\s/g"").length;



  // Calculate word count (space as a separator)

  const wordCount = text.trim() === "" ? 0 : text.trim().split(/\s+/).length;



  return (

    <div className="container">

      <div className="input">

        <textarea

          id="input"

          placeholder="Enter a text"

          value={text}

          onChange={handleChange}

        />

      </div>

      <div className="result">

        <div className="character-count">

          // Display the character count

          <span id="characterCount">{characterCount} </span>

          <span>Characters</span>

        </div>

        <div className="character-count-without-spaces">

          <span id="characterCount">{characterCountWithoutSpaces} </span>

          <span>Characters (Excluding Spaces)</span>

        </div>

        <div className="word-count">

          // Display the word count

          <span id="wordCount">{wordCount} </span>

          <span>Words</span>

        </div>

      </div>

    </div>

  );

}



export default CharacterCounter;

With adding the logic to the component, you will now be able to see the entire working of the application from input to output. The output will look like this

Congratulations 🎉!

You have successfully created your own character counter application.

In the next module, we will look into the steps to deploy the project using vercel.

See you in the next module!