How to Build a Textarea with Line Numbers in React
A textarea has no built-in line numbers, so I place a div with the numbers stacked vertically to the left of the textarea. The numbers are generated from the newline count in the input string, and when the textarea scrolls, the number column scrolls by the same amount. If you turn off wrapping so that one line equals one number, the numbers stay aligned with their lines.
In this article, I build an input for something like a config file and bold the number of the line where the caret is. The way to move the number column and the way to find the caret's line each had a pitfall I ran into during testing, so I include those results.
The test environment was Ubuntu 24.04, Node.js 22.23.4, and Chromium 153. I used React 19.3.1, TypeScript 7.0.2, esbuild 0.28.2, and Playwright 1.63.0. I type-checked the .tsx file with tsc, transformed it with esbuild, and used Playwright to drive Chromium. I removed the --hide-scrollbars flag that Playwright adds in headless mode, so the scrollbars take up width, and I tested in that state. Running the development build (with StrictMode) produced no errors or warnings in the console. I did not test Firefox, Safari, smartphone browsers, IME composition for Japanese input, screen reader announcements, or speed with strings of more than several thousand lines.
![In an input with six lines of settings, pressing Enter and adding "file = "app.log"", "rotate = 7", an empty line, and "[cache]" increases the line numbers from 7 to 10. When the input scrolls, the number column scrolls up with it. Pressing ↑ three times moves the bold number from 10 to 7. Scrolling up with the wheel returns the number column to line 1. Clicking line 2 makes the bold number 2.](https://neko-note.org/wp-content/uploads/2026/11/react-line-number-textarea-line-number-textarea.gif)
A component that places the line number column and textarea side by side
The component is LineNumberTextarea below. An outer div places the line number column and the textarea side by side. The textarea manages its value with value and onChange, the same way as the state-variable example in the official reference.
import { useEffect, useRef, useState, type CSSProperties, type UIEvent } from 'react';
type Props = {
id: string;
value: string;
onChange: (value: string) => void;
rows?: number;
};
// Line number of the caret (counted from 1)
function caretLine(el: HTMLTextAreaElement) {
const pos = el.selectionDirection === 'backward' ? el.selectionStart : el.selectionEnd;
return el.value.slice(0, pos).split('\n').length;
}
export function LineNumberTextarea({ id, value, onChange, rows = 8 }: Props) {
const textareaRef = useRef<HTMLTextAreaElement>(null);
const numbersRef = useRef<HTMLDivElement>(null);
const [current, setCurrent] = useState(1);
const count = value.split('\n').length;
// Recompute the caret's line every time the caret moves
useEffect(() => {
const el = textareaRef.current!;
const update = () => setCurrent(caretLine(el));
el.addEventListener('selectionchange', update);
return () => el.removeEventListener('selectionchange', update);
}, []);
// Shift the line number column up to match the textarea's scroll
const handleScroll = (e: UIEvent<HTMLTextAreaElement>) => {
const top = e.currentTarget.scrollTop;
if (numbersRef.current) numbersRef.current.style.transform = `translateY(${-top}px)`;
};
return (
<div className="ln-wrap" style={{ '--digits': String(count).length } as CSSProperties}>
<div className="ln-gutter" aria-hidden="true">
<div ref={numbersRef}>
{Array.from({ length: count }, (_, i) => (
<div key={i} className={i + 1 === current ? 'ln-current' : undefined}>
{i + 1}
</div>
))}
</div>
</div>
<textarea
ref={textareaRef}
id={id}
className="ln-input"
value={value}
rows={rows}
spellCheck={false}
onChange={(e) => onChange(e.target.value)}
onScroll={handleScroll}
/>
</div>
);
}
The number of lines is counted with value.split('\n').length. An empty string also gives 1, so the display shows "1" even when nothing has been typed.
I added aria-hidden="true" to the line number column to remove it from the accessibility tree. I typed "a = 1" and "b = 2" on two lines and dumped the tree with Playwright. The numbers did not appear, and only one labeled textbox remained.
- text: 設定ファイル
- textbox "設定ファイル": a = 1 b = 2
- button "クリア"
On the using side, you just hold the string in useState and pass it down.
import { useState } from 'react';
import { LineNumberTextarea } from './LineNumberTextarea';
export function App() {
const [code, setCode] = useState('');
return (
<form onSubmit={(e) => e.preventDefault()}>
<label htmlFor="code">設定ファイル</label>
<LineNumberTextarea id="code" value={code} onChange={setCode} />
<button type="button" onClick={() => setCode('')}>
クリア
</button>
</form>
);
}
I pressed Enter to add lines up to 20, then clicked "Clear" while the textarea was scrolled. The textarea's scrollTop went back to 0, and the number column returned to translateY(0px). Only "1" remained, and the bold moved to line 1.
CSS that matches line heights and disables wrapping
To align the numbers with their lines, the font (size and line height) and the top and bottom padding must be the same for the line number column and the textarea. I put the shared rules into one block.
.ln-wrap {
display: flex;
border: 1px solid #9aa5ab;
border-radius: 6px;
overflow: hidden;
background: #fff;
}
.ln-wrap:focus-within {
outline: 2px solid #00c8e8;
outline-offset: 1px;
}
/* Always keep the line-height settings the same for the line number column and the textarea */
.ln-gutter,
.ln-input {
margin: 0;
padding-block: 8px;
font: 14px/1.6 "Noto Sans Mono CJK JP", monospace;
}
.ln-gutter {
flex: none;
contain: size; /* Keep the height from growing with the number of lines; match the textarea's height */
overflow: hidden;
width: calc(var(--digits) * 1ch);
min-width: 2ch;
padding-inline: 8px;
text-align: right;
color: #9aa5ab;
background: #eefafd;
user-select: none;
}
.ln-current {
color: #067a98;
font-weight: bold;
}
.ln-input {
flex: 1;
min-width: 0;
padding-inline: 8px;
border: 0;
outline: none;
resize: vertical;
white-space: pre;
overflow: auto;
color: #1f2a30;
}
contain: size is a declaration that sizes an element without considering its contents. Without it, the textarea, placed next to the column in a flex row, is stretched to the height of the number column. When I entered 30 lines and compared, the textarea was 195px tall with contain: size (the 8 lines from rows={8}). Without it, the textarea was 688px tall, stretched until all 30 lines were visible.
The width of the number column is set in ch units, with the digit count passed through the CSS variable --digits. ch is the width of the "0" glyph in the font. I changed the line count and compared the width of the largest number with the inner width of the column.
| Lines | Width of last number | Inner width of column |
|---|---|---|
| 9 lines | 14px | 14px (min-width: 2ch) |
| 99 lines | 14px | 14px |
| 100 lines | 21px | 21px |
| 1000 lines | 28px | 28px |
In every case, the numbers fit inside the column. When the count goes from 99 to 100, the column widens by one character, and the textarea gets narrower by that amount.
I also added user-select: none to the number column. When I dragged a selection from the top-left of the page down past the "Clear" button, the selected text was "設定ファイル\n\nクリア" (the Japanese for "config file", a blank line, and "Clear"), with no numbers included.
Wrapping is turned off by setting white-space: pre on the textarea. The MDN textarea page says that wrap="off" is a non-standard value meant to look like white-space: pre, so this article uses CSS instead of the attribute. With four lines, one of them long, the textarea kept four lines, and the long line overflowed by 1,017px and could be scrolled horizontally.
Move the number column with transform, not scrollTop
Another approach is to set the number column's scrollTop to the same value as the textarea's. With that approach, when a line overflows horizontally, the numbers drifted down by 15px when scrolled to the bottom.
I put a long string on only line 5 of 30 lines, scrolled to the bottom with the wheel, and compared the results.
[scrolltop・long] textarea: scrollTop=508 scrollHeight=688 clientHeight=180
[scrolltop・long] 行番号の列: scrollTop=493 scrollHeight=688 clientHeight=195 transform=なし
[scrolltop・long] 行番号と行の上端の差(最大): 15px、列のいちばん下に見える行番号: 30
The textarea has a horizontal scrollbar below it, so its visible height (clientHeight) is 180px. The number column has no scrollbar and stays at 195px. The content height is 688px for both, so the textarea can scroll up to 508px, while the number column can only scroll to 493px. The number column stopped at 493px, so the numbers drifted down by the 15px difference. With 30 lines and no line overflowing horizontally, both could scroll to 493px, and no drift appeared.
In the finished version, which moves the column with transform: translateY(), the same string moved to translateY(-508px) regardless of the scroll limit of the number column. The largest gap between a number and the top edge of its line is 0.3px.
[final・long] textarea: scrollTop=508 scrollHeight=688 clientHeight=180
[final・long] 行番号の列: scrollTop=0 scrollHeight=688 clientHeight=195 transform=translateY(-508px)
[final・long] 行番号と行の上端の差(最大): 0.3px、列のいちばん下に見える行番号: 30

The translateY value is written directly to the style.transform of the element obtained by ref, not through React state. Even when I pressed Enter to add lines up to 20, the number column moved to translateY(-260px), matching the amount the textarea had scrolled by itself (scrollTop=260).
Without disabling wrapping, numbers drift from their lines
The third image above was made by removing white-space: pre, so the long line wraps inside the textarea. Only four numbers appear, one per newline, but the display has eight visual lines. The "3" and "4" sit beside the continuation of the wrapped second line, and the real third and fourth lines get no numbers.
The code in this article generates one number per newline, so it cannot be used as-is with an input that wraps. It assumes a code input, and that is why wrapping is turned off.
Find the caret's line with selectionchange
The number of the caret's line is found by adding 1 to the count of newlines before the caret position. Normally, the caret position is the end of the selection (selectionEnd). Only when selectionDirection is "backward" (the selection was made from back to front) is the start of the selection (selectionStart) used. When I selected from the end of line 3 up to line 1 with Shift+↑, the bold moved to line 1.
I also tried recomputing the line with React's onSelect and onChange. The official reference for onSelect says it is called after the selection changes, including when the selection is empty and when editing. Typing, ↑, Ctrl+End, and Shift+↑ selections all gave the correct line. However, after selecting from the end of line 3 up to line 1 in the same way, clicking inside the selection on line 2 moved the caret to line 2, but the bold stayed on line 1.
--- Line where the caret is (onselect) ---
Shift+↑ を2回(後ろから前へ選択): 1
選択範囲の中の2行目をクリック: 1 (キャレットは2行目)
So I listen for the selectionchange event fired by the textarea. Inside useEffect, I register it with addEventListener on the textarea obtained by ref. With the same operation, the bold moved to line 2.
--- Line where the caret is (final) ---
Shift+↑ を2回(後ろから前へ選択): 1
選択範囲の中の2行目をクリック: 2 (キャレットは2行目)
According to MDN's compatibility table, selectionchange fires on a textarea starting with Chrome 127, Firefox 92, and Safari 18. In earlier versions of Chrome and Safari, the event fires on document instead of the textarea. The code in this article registers the listener on the textarea, so it targets browsers from those versions onward.





