Implementing a word cloud with React

I actually had this come up as an interview question once, and it was more of a theoretical discussion on how I would implement it, as opposed to actually having me white board it/live code it. I thought it would be good practice to re-visit this and implement a quick solution.

I opted to create a helper function that takes an object that contains the word itself, as well as the count – or frequency – that each word appears. The function simply returns a string based on whether or not certain conditions are made. For example, if the word count is less than or equal to 4, it will return the string “small”. We can then use that to set the fontSize to “small”. Let’s take a look at the code:

import React from "react";
import "./word-cloud.styles.css";

const WordCloud = () => {
  const words = [
    { word: "car", count: 3 },
    { word: "electric", count: 8 },
    { word: "engine", count: 5 },
    { word: "motor", count: 11 },
    { word: "brake", count: 1 },
  ];

  const applyStyling = ({ word, count }) => {
    if (count <= 2) {
      return "x-small";
    } else if (count <= 4) {
      return "small";
    } else if (count <= 6) {
      return "medium";
    } else if (count <= 8) {
      return "large";
    } else if (count >= 9) {
      return "x-large";
    } else {
      return "medium";
    }
  };

  return (
    <div className="main-div">
      {words.map((word, index) => (
        <li key={index} className="word-list-item">
          <p style={{ fontSize: applyStyling(word) }}>{word.word}</p>
        </li>
      ))}
    </div>
  );
};

export default WordCloud;

I opted to go with in-line styling for this specific example instead of creating many classes that each set the font-size property to the proper values. If you wanted to implement a CSS class-based implementation, instead of a style attribute, you’d utilize the className attribute, and assign the returned value from the applyStyling function to that.