Implementation of Character Counter

Step-by-Step Implementation

In this module we will get our hands dirty with the actual implementation of a character counter application in React JS. Let’s get started with the initial project setup!

Set up the environment

As the first step to get started with the implementation, we need to set up the environment for the project. Follow the below steps to set up the project.

  • Open VScode
  • Create a new folder named ‘character-counter’
  • Open ‘new terminal’
  • Enter the command ‘npx create-react-app app’. This will create a new React JS project with the name ‘app’.
  • Once the installation is complete, enter the command ‘cd app & npm start’ to start the React JS application in localhost:3000.

After removing the unnecessary files and folders, the app directory will look like this.

Create Application Structure

In this step, we will create the basic structure to the application such as container, text input areas and display area. This will make it easy to view the elements we need for the application.

  • For the character counter, we need one text area to get the dynamic input from the user and one display area to display the results.
  • As the first stage, create a components folder in the src directory and create a file with the name ‘CharacterCounter.jsx’

  • Now, copy and paste the code to create the basic structure of the application.
// character counter.jsx 


// Functional Component to Create the character counter 


function CharacterCounter() {
    return (
   // The main container 
    <div>
// The input container 
      <div>
        // The text area
        <textarea
          id="input"
          placeholder="Enter a text"
          value={text}
         />
      </div>
      // The result container
      <div>
       // The Character count section
        <div>
          <span id="characterCount">0</span>
          <span>Characters</span>
        </div>
        // The word count section
        <div>
          <span id="wordCount">0</span>
          <span>Words</span>
        </div>
      </div>
    </div>
  );
}


export default CharacterCounter;
  • After the character counter component export, you need to import the component in the main component ‘App.jsx’ since it is the entry point for your application.
  • Modify the code in ‘App.jsx’ file similar to the below code.
// App.jsx 


// Import the character counter component 
import CharacterCounter from "./components/CharacterCounter";


function App() {
  return (
    // The main container
    <div>
      // The header container
      <div>
  // The application title
        <h1>Character Counter App</h1>
      </div>
    // The Character counter component
      <CharacterCounter />
    </div>
  );
}


export default App;
  • After updating the App component, you will see the following result.

Apply Styles to the Application

The next step is to add styles to each element to make it visually appealing using CSS. We can create n styling files one for each component. In this project, we will create two css files, one for the character counter component and another for the App component.

  • Modify the character counter component to add styling for each element. Using the ‘className’ attribute, we can match the styling to the element. Make sure to import the style file into the component.
// CharacterCounter.jsx


import "./CharacterCounter.css";


function CharacterCounter() {
  return (
    <div className="container">
      <div className="input">
        <textarea
          id="input"
          placeholder="Enter a text"
          value={text}
        />
      </div>
      <div className="result">
        <div className="character-count">
          <span id="characterCount">0</span>
          <span>Characters</span>
        </div>
        <div className="character-count-without-spaces">
          <span id="characterCount">0</span>
          <span>Characters (Excluding Spaces)</span>
        </div>
        <div className="word-count">
          <span id="wordCount">0</span>
          <span>Words</span>
        </div>
      </div>
    </div>
  );
}


export default CharacterCounter;
  • The next step is to create a styling file for character counter. Create a file in the component folder ‘ChacterCounter.css’. And write styles for each element.
/* ChacterCounter.css */


/* Main body styling */
body{
    height: 100vh;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: rgb(224, 223, 223);
}


/* Main container styling */
.container{
    width: max-content;
}


/* Text area styling */
#input{
    resize: none;
    height: 200px;
    width: 700px;
    border: 3px solid black;
    padding: 2px;
    margin: 25px 0;
    font-size: 1rem;
}


/* Display area styling */
.result{
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    font-size: 1.5rem;
}
  • Now, let’s add some styling to the App component.
// App.js


import "./App.css";
import CharacterCounter from "./components/CharacterCounter";


function App() {
  return (
    <div className="App">
      <div className="header">
        <h1 className="title">Character Counter App</h1>
      </div>
      <CharacterCounter />
      <a href="https://www.guvi.in/" className="copywright">
        Made by Guvi💚
      </a>
    </div>
  );
}


export default App;
  • Modify the App.css file to include new stylings.
/* App.css */


*{
  margin: 0;
  padding: 0;
}
.App{
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.title{
  font-size: 2rem;
  margin: 20px;
}
.copywright{
  margin-top: 50px;
}
  • Once you add the styling, the application will look like the below output.

Add Calculation to the 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 lesson, we will look into the steps to deploy the project using vercel.

See you in the next lesson!