How to Display Frequent Words in Text as a Word Cloud in React
A word cloud can be built by counting words, setting each font size from its count, and placing the largest words first in positions where they don't overlap. Each position is searched for by starting at the center of the frame and moving outward along a spiral. To check for overlap before drawing, you need to know each word's width, so the width is measured on a canvas that is never shown on screen.
Here I built a WordCloud component. You pass it words sorted by count, from most to least frequent, and it lays them out in a 360px × 240px frame. For counting, it uses countWords() from the earlier article "How to Count Word Frequencies in Text with React" as is, with a setting that excludes words written only in hiragana.
The test environment was Ubuntu 24.04, Node.js 22.23.4, and Chromium 153, with Noto Sans CJK JP as the font. I used React 19.3.1, TypeScript 7.0.2, esbuild 0.28.2, and Playwright 1.63.0. I type-checked the .tsx with tsc, transformed it with esbuild, and rendered a development build wrapped in StrictMode in Chromium with Playwright. I did not test Firefox, Safari, real smartphones, or actual reading by a screen reader. I also did not cover loading and using web fonts, vertical text, words rotated at an angle, designs where the frame width changes with the screen, or server-side rendering.

Setting the font size from the count
The font size maps the least frequent word to 14px and the most frequent word to 56px, and assigns sizes in between. If font size were directly proportional to count, words with mid-range counts would look too small for their counts. Font size grows both vertically and horizontally, so the visual area grows with the square of the font size.
For that reason, I made 'sqrt', which scales by the square root of the count, the default. For comparison, 'linear', which uses the count directly, can also be selected.
export type Scale = 'linear' | 'sqrt';
// Map count to a font size between minPx and maxPx. 'sqrt' compresses the differences with a square root
export function fontSizeOf(
count: number, minCount: number, maxCount: number,
minPx: number, maxPx: number, scale: Scale = 'sqrt',
): number {
if (maxCount === minCount) return maxPx; // If all counts are equal, make them all the largest size
const f = scale === 'sqrt' ? Math.sqrt : (n: number) => n;
const t = (f(count) - f(minCount)) / (f(maxCount) - f(minCount));
return Math.round(minPx + (maxPx - minPx) * t);
}
I used Node.js to calculate sizes for words with counts of 12, 6, 3, 2, and 1.
回数 : 12 6 3 2 1
linear (px) : 56 33 22 18 14
sqrt (px) : 56 39 26 21 14
6回の語の面積(12回の語を1とする): linear 0.35 / sqrt 0.49
A word with 6 occurrences, half of the 12-occurrence word, had an area of 0.35 times that of the 12-occurrence word with 'linear' and 0.49 times with 'sqrt'. With 'sqrt', the ratio of counts is closer to the ratio of visual areas. When all counts are the same, every word is set to 56px to avoid dividing by zero.
Using the sample text (the word for cat, neko, appears 6 times, nemuri (sleep) 3 times, 7 words appear 2 times, and 11 words appear once), the sizes were as follows. With 'sqrt', words with 2 occurrences grow from 22px to 26px, which makes the difference from 1-occurrence words easier to see.
見本の文章 6/3/2/1回: linear 56 31 22 14 / sqrt 56 35 26 14

Finding a non-overlapping position along a spiral
The placement logic is in layout(). It receives words from most to least frequent. For each word, it starts at the center of the frame and moves along a spiral that gradually expands outward. It places the word at the first position where it doesn't overlap any word already placed and doesn't extend past the frame.
// Whether two boxes (x, y is the top-left corner) overlap when kept at least gap apart
function overlaps(a: Placed, b: Placed, gap: number): boolean {
return a.x < b.x + b.width + gap && b.x < a.x + a.width + gap
&& a.y < b.y + b.height + gap && b.y < a.y + a.height + gap;
}
// Place words in order from largest to smallest. Starting from the center, move outward along a spiral
// and place each word at the first position where it doesn't overlap any placed word and stays inside the frame
export function layout(
words: readonly Sized[], measure: (word: string, fontSize: number) => Size,
area: Size, gap = 2, step = 3,
): { placed: Placed[]; skipped: Sized[] } {
const placed: Placed[] = [];
const skipped: Sized[] = [];
const cx = area.width / 2;
const cy = area.height / 2;
const aspect = area.width / area.height; // For a wide area, make the spiral spread horizontally
const maxR = Math.hypot(cx, cy);
for (const w of words) {
const { width, height } = measure(w.word, w.fontSize);
let spot: Placed | null = null;
// Archimedean spiral r = (step / 2π)θ. Each turn moves outward by step
for (let theta = 0, r = 0; r <= maxR; ) {
const box: Placed = {
...w, width, height,
x: cx + r * Math.cos(theta) * aspect - width / 2,
y: cy + r * Math.sin(theta) - height / 2,
};
const inside = box.x >= 0 && box.y >= 0
&& box.x + width <= area.width && box.y + height <= area.height;
if (inside && placed.every((p) => !overlaps(box, p, gap))) {
spot = box;
break;
}
theta += step / Math.max(r, step); // Move along the spiral by roughly step each time
r = (step / (2 * Math.PI)) * theta;
}
if (spot) placed.push(spot);
else skipped.push(w);
}
return { placed, skipped };
}
The types add size and position to the result of countWords().
export type Size = { width: number; height: number };
export type Sized = WordCount & { fontSize: number };
export type Placed = Sized & { x: number; y: number; width: number; height: number };
The spiral is one where the distance r from the center is proportional to the angle theta. Each turn moves outward by the same amount, which is step (3px here), so the search is equally fine from the inside to the outside. To fit the wide frame, the horizontal direction is stretched by 1.5× (360 ÷ 240). If the angle increased by a fixed amount each time, the distance covered in one step would grow farther out, and the search points would become sparser. So the angle increases by step / max(r, step) each time, which moves along the unstretched spiral by about 3px per step. (While r is smaller than step near the center, the angle increases by 1 radian per step.)
Overlap is checked using rectangles that enclose each word. No other word fits into gaps in the character shapes, such as the space beside the final "ri" of nemuri (sleep).
No random numbers are used, so the same words and counts always produce the same positions. I ran the layout twice in Node.js with a provisional width (the width of one character equals the font size), and the results matched.
猫 x=152.0 y=86.0 w=56 h=68
窓辺 x=73.3 y=104.6 w=76 h=46
眠り x=210.3 y=82.3 w=76 h=46
庭 x=212.8 y=131.6 w=28 h=34
同じ入力で2回並べて同じ結果: true
Measuring text width with canvas and drawing in React
To check overlap, you need the width of each word before drawing it. layout() takes a measure function as an argument, so in the browser I pass a function that uses a canvas.
measureText() on canvas returns a TextMetrics object with values such as the string's width (MDN page for measureText()). The shape of the characters is set by font, which takes a string written in the same format as CSS font (MDN page for font). I set the same weight, size, and font as the drawn text so they match.
import type { WordCount } from './words';
import { fontSizeOf, layout, type Scale } from './cloud';
const FONT = '"Noto Sans CJK JP", "Hiragino Sans", sans-serif';
const LINE_HEIGHT = 1.2;
// Measure text width on an off-screen canvas (created once, on first use)
let ctx: CanvasRenderingContext2D | null = null;
function measureText(word: string, fontSize: number) {
ctx ??= document.createElement('canvas').getContext('2d')!;
ctx.font = `bold ${fontSize}px ${FONT}`;
return {
width: Math.ceil(ctx.measureText(word).width),
height: Math.ceil(fontSize * LINE_HEIGHT),
};
}
type Props = {
words: WordCount[]; // words and counts, sorted by count (highest first)
width: number;
height: number;
limit?: number; // Maximum number of words to show
scale?: Scale;
maxFontSize?: number; // Font size of the most frequent word (px)
};
export function WordCloud({ words, width, height, limit = 40, scale = 'sqrt', maxFontSize = 56 }: Props) {
// Don't keep the layout result in state; compute it from props on every render
const top = words.slice(0, limit);
const max = top[0]?.count ?? 0;
const min = top[top.length - 1]?.count ?? 0;
const sized = top.map((w) => ({ ...w, fontSize: fontSizeOf(w.count, min, max, 14, maxFontSize, scale) }));
const { placed, skipped } = layout(sized, measureText, { width, height });
return (
<figure className="word-cloud">
<ul aria-label="よく出る言葉(多い順)" style={{ position: 'relative', width, height }}>
{placed.map((w, i) => (
<li
key={w.word}
style={{
position: 'absolute', left: w.x, top: w.y,
fontSize: w.fontSize, lineHeight: LINE_HEIGHT,
fontFamily: FONT, fontWeight: 'bold', whiteSpace: 'nowrap',
color: i === 0 ? '#d85878' : i % 2 ? '#067a98' : '#1f2a30',
}}
>
{w.word}
<span className="visually-hidden">({w.count}回)</span>
</li>
))}
</ul>
<figcaption>
{placed.length}語を表示
{skipped.length > 0 && `(枠に入りきらなかった${skipped.length}語は省略)`}
</figcaption>
</figure>
);
}
Each word is placed in an <li> with position: absolute at the top-left position that layout() decided. The height is set with line-height of 1.2, and the measurement also uses 1.2 times the font size.
In Chromium, I compared the widths measured on canvas (rounded up) with the widths of the rendered <li> elements. The difference was between 0 and 0.98px. The measured width was never smaller than the actual width. When I counted overlaps and extensions past the frame using the rectangles of the rendered <li> elements, there were zero of both.
canvas で測った幅 − 表示の幅: 最小 0.00 px 最大 0.98 px
Adding counts for screen readers
The visual display conveys counts through font size, but screen readers don't convey that. So the whole list is labeled "frequent words, most to least" (the aria-label is in Japanese), and after each word, a count such as "(6 times)" is included but hidden visually. .visually-hidden clips the element to 1px using the following CSS.
.visually-hidden{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap}
Because the <span> is position: absolute, it does not count toward the width of the <li>. When I read the accessibility tree with Playwright, the words appeared as a list in order from most to least frequent.
- list "よく出る言葉(多い順)":
- listitem: 猫 (6回)
- listitem: 眠り (3回)
- listitem: 窓辺 (2回)
- listitem: 来 (2回)
- listitem: 窓 (2回)
Connecting to the text input
The text in the input is kept in state. On each render, the word counts are computed with countWords() and passed to WordCloud. The ?max=32 line was added so I could change the font size later to test it.
import { useId, useState } from 'react';
import { countWords } from './words';
import { WordCloud } from './WordCloud';
const SAMPLE =
'猫は窓辺で眠ります。朝になると、猫は台所に来て、ごはんを待ちます。' +
'ごはんを食べた猫は、また窓辺に戻って眠ります。' +
'雨の日の猫は、窓の外をじっと見ています。窓の外には庭があり、庭には小鳥が来ます。' +
'小鳥を見つけた猫は、しっぽを振ります。夜になると、猫は毛布の上で眠ります。';
export function App() {
const [text, setText] = useState(SAMPLE);
const textId = useId();
const words = countWords(text, true); // Don't count words written only in hiragana
// Only for testing: ?max=32 changes the largest font size
const max = Number(new URLSearchParams(location.search).get('max')) || 56;
return (
<main>
<label htmlFor={textId}>文章</label>
<textarea id={textId} rows={5} value={text} onChange={(e) => setText(e.target.value)} />
<WordCloud words={words} width={360} height={240} maxFontSize={max} />
</main>
);
}
When I used Playwright to add the sentence "The cat by the window is watching the small bird." to the end of the text, the words for by the window, small bird, and see each appeared 3 times, and their sizes grew from 26px to 33px. When I replaced the text with the English sentence cat dog cat bird cat dog fish, cat was set to 56px and dog to 38px, and four words were shown. When I emptied the text, the caption showed "0 words shown". In every case, there were zero overlaps and zero extensions past the frame, and the console showed no errors or warnings.
Words that don't fit and layout time
If no position is found for a word after searching the spiral to the corners of the frame, the word is not displayed and goes into skipped. The caption below the frame shows how many words were omitted. I tested 40 long English words made by adding the letters a to d to the end of English words. The word ranked first appeared 40 times, the second 20 times, and so on, so the count dropped with rank. Only 10 words could be displayed.
--- 40 long English words
caption : 10語を表示(枠に入りきらなかった30語は省略)
words : strawberrya(56px) blueberrya(41px) raspberrya(36px) watermelona(28px) grapefruita(25px) cranberrya(22px) cranberryb(17px) blueberryc(17px) raspberryc(17px) cranberryd(14px)
The word pineapplea, which appeared 10 times and ranked fourth, was omitted, but cranberrya and other words with lower counts were included. This is because layout() skips words that can't be placed and moves on to the next word. When I lowered the largest font size to 32px, 24 words could be displayed for the same text. When many words are omitted, making the text smaller allows more words to fit in the frame.
--- 40 long English words (largest font size set to 32px)
caption : 24語を表示(枠に入りきらなかった16語は省略)
I measured the time layout() took inside Chromium. I ran 3 warm-up runs and then measured 11 times.
見本の文章(20語、置けた 20 語): 中央値 2.4ms 最小 1.7ms 最大 3.1ms
長い英単語 40 種類(40語、置けた 10 語): 中央値 37.8ms 最小 36.8ms 最大 43.6ms
The long-word case took more than ten times as long. The number of words doubled, and each word that couldn't be placed had its spiral searched to the end before being skipped. So when many words can't be placed, the time increases.
This component re-lays out the words on every keystroke. The React official reference says that if a calculation takes 1ms or more in total, you may consider memoizing it with useMemo. The times above are for layout() alone, measured without React. I do not use useMemo here. useMemo compares dependency values with the previous values using Object.is, but countWords() in App returns a new array on every render. So even if words is in the dependency array, the calculation runs again regardless of whether the contents are the same. Memoization would not reduce the calculation.





