Let's Build Word Frequency Counter using ReactJS

Let's Build Word Frequency Counter using ReactJS

Reactjs

You might get an idea of what a word frequency counter would be. Basically, a platform where you write something and it gives out the frequency of each word in that paragraph. We will build this in the simplest manner with not much CSS styling and keeping simple to understand.

Core React Concepts Used:-

  1. useState Hook
  2. Basic event Handling (onChange Event)
  3. Mapping array
  4. passing Props

Core JS concepts used:-

  1. Looping using Map
  2. Using Objects

So now let's start right away:-

The basic idea while building the app was to have two separate components for the entire react app, one containing a text area and secondly a result section where the count of each word appears dynamically.

You can follow along with the code here:- link

So a main App.js file only renders a component containing Input.js and Input being the child component and the result being the child component of Input as we had to pass props from Input to results.

The App.js contains a single component being rendered and Input.js containing Result.js being rendered as its child component.

So now iterating over the core React concepts used:-

  1. useState Hook

In Input.js is being used to set the input text from the user to a predefined empty text which will be then passed to the results component.

code:- const [text, setText] = useState('')

  1. Basic Event Handling

The event called onChange is used, basically, whenever there is a change in the text area the useState hook comes into action and sets the text.

code:-

 function handlechange(event) {
    let newtext = event.target.value;
    settext(newtext);
  }
  1. Mapping Array:-

When we have a list of keys and their count, we have to iterate through each and show the result for each and we use the map to do so

code:-

<div className="res-section">
      {keys.map((ele) => (
        <div className="grid-item">
          {ele} : {newObj[ele]}
        </div>
      ))}
</div>
  1. passing Props

Props are basically data that can be passed to the children and the same happens for Input and Result. We pass Input data to the result to show the output.

code:-

<Result text={text} />

here text is the prop passed.

Core JS Concepts We have covered the loop by using the map

  1. Using Objects

Objects are used basically to keep track of the count of each word.

code:-

const text = props.text.toLowerCase();
const textArr = text.split(" ");
const obj = {};
function giveFreq() {
  for (let i = 0; i <= textArr.length; i++) {
    obj[textArr[i]] = 0;
  }
  for (let i = 0; i <= textArr.length; i++) {
    obj[textArr[i]]++;
  }
  return obj;
}
const newObj = giveFreq();
let keys = Object.keys(newObj); 
keys = keys.slice(0, keys.length - 2);

Yeah, that's it for this project. I am working on a bunch of other small projects. Will be following the same structure to introduce it to you. Stay tuned!!