日本語

Indent with the Tab Key in a React Textarea

​​React​Accessibility,Playwright,textarea,TypeScript

In a textarea, pressing Tab normally does not indent. Focus moves to the next field. I receive Tab in onKeyDown, call preventDefault(), and insert the indent spaces with document.execCommand('insertText'). This makes the textarea indent like an editor, and Ctrl+Z can undo the indent. The cost is that Tab can no longer leave the textarea, so I make Esc followed by Tab move focus to the next field.

I built and checked the parts for indenting several lines at once and for Shift+Tab outdenting.

Note

Tested on Ubuntu 24.04, Node.js 22.23.4, and Chromium 153. I used React 19.3.1, @types/react 19.3.0, TypeScript 7.0.2, esbuild 0.28.2, and Playwright 1.63.0. I type-checked the .tsx with tsc, converted it with esbuild, and operated headless Chromium with Playwright. I did not test Firefox or Safari, smartphone soft keyboards, pressing Tab during Japanese input (IME) conversion, screen reader announcements, or a textarea inside a dialog that closes with Esc. The labels in the GIF are in Japanese.

Pressing Tab at the start of line 2 indents line 2. Selecting all and pressing Tab indents every line, and Shift+Tab outdents them back. Pressing Esc and then Tab moves focus to the Save button (its label in the image is Japanese, meaning "Save"). The box at the bottom right shows the key pressed, the bar at the top shows the step number, and the circle shows the mouse position. These were overlaid for the GIF.
Pressing Tab on line 2, Tab with everything selected, Shift+Tab, Esc, then Tab, in that order. Each changed part turns pink only at the moment it changes.

Without stopping Tab at keydown, focus moves

I tried a textarea with no Tab handling. I put the caret at the start of line 2 and pressed Tab. The value did not change, and focus moved to the Save button after the textarea. In the test output, the textarea is referred to as "body."

text
2行目の先頭で Tab
  値 "function meow() {\nconsole.log(\"にゃー\");\n}" | 選択 18〜18 | フォーカス: ボタン「保存」

As the W3C ARIA Authoring Practices Guide's keyboard interface explanation describes, moving focus from one widget to another with Tab and Shift+Tab is standard behavior in every environment. To use Tab for indenting, I receive Tab in onKeyDown and stop that behavior with e.preventDefault().

I stop only Tab and Shift+Tab. If ctrlKey, altKey, or metaKey is set, I do nothing. I checked defaultPrevented on the Tab keydown for each key combination. Only Tab and Shift+Tab were stopped. Ctrl+Tab and Alt+Tab were not.

text
Tab        止めた
Shift+Tab  止めた
Ctrl+Tab   止めていない
Alt+Tab    止めていない

Calculate the range to change first

I put the logic for deciding what to change into computeIndent, which does not depend on React. It takes the textarea's value and selection, and returns the range to replace (from to to), the text to insert in its place (insert), and the selection after the replacement.

ts
export const INDENT = '  '; // one indent level (two half-width spaces)

export type IndentEdit = {
  from: number; // start of the range to replace
  to: number; // end of the range to replace
  insert: string; // text to insert in its place
  selStart: number; // selection after the replacement
  selEnd: number;
};

// Returns the change for pressing Tab (outdent = false) or Shift+Tab (outdent = true). Returns null if nothing changes
export function computeIndent(value: string, start: number, end: number, outdent: boolean): IndentEdit | null {
  const multiLine = value.slice(start, end).includes('\n');
  // If the selection is within one line, insert the indent at the caret (or over the selected range)
  if (!outdent && !multiLine) {
    const caret = start + INDENT.length;
    return { from: start, to: end, insert: INDENT, selStart: caret, selEnd: caret };
  }
  // Take the lines touched by the selection, from the start of the first line to the end of the last line
  const from = value.lastIndexOf('\n', start - 1) + 1;
  // If the selection ends at the start of a line, do not include that line
  const last = end > start && value[end - 1] === '\n' ? end - 1 : end;
  const lineEnd = value.indexOf('\n', last);
  const to = lineEnd === -1 ? value.length : lineEnd;
  const lines = value.slice(from, to).split('\n');

  if (!outdent) {
    return {
      from, to,
      insert: lines.map((line) => INDENT + line).join('\n'),
      selStart: start + INDENT.length,
      selEnd: end + INDENT.length * lines.length,
    };
  }
  // Remove one leading tab, or up to the length of INDENT in spaces
  const removed = lines.map((line) => (line.startsWith('\t') ? 1 : line.match(/^ */)![0].slice(0, INDENT.length).length));
  if (removed.every((n) => n === 0)) return null;
  const total = removed.reduce((a, b) => a + b, 0);
  return {
    from, to,
    insert: lines.map((line, i) => line.slice(removed[i])).join('\n'),
    selStart: Math.max(from, start - removed[0]),
    selEnd: Math.max(from, end - total),
  };
}

When the selection stays within one line, Tab only inserts two spaces at the caret. If text is selected, the selected text is replaced by the spaces, just as when typing. When the selection spans multiple lines, or for Shift+Tab, every touched line is taken whole, and spaces are added or removed per line.

These are results from several cases I tried in Node.js. The first four start from "a\nb\nc" (three lines: a, b, c). The next three start from " a\n b\n\tc\nd" (four lines: a with four spaces, b with two spaces, c with a tab, and d with no indent). The last starts from " " (one line with two half-width spaces).

"Before" is the value and selection before the operation, and "After" is the value and selection after it. The part between [ and ] is the selection, and [] is the caret position. The numbers in parentheses are the start to end positions passed to computeIndent (counting from 0, with the newline \n and the tab \t each counted as one character).

text
キャレットが b の前で Tab(選択 2〜2)
  前 "a\n[]b\nc"
  後 "a\n  []b\nc"
「b」を選んで Tab(選択 2〜3)
  前 "a\n[b]\nc"
  後 "a\n  []\nc"
a〜b を選んで Tab(選択 0〜3)
  前 "[a\nb]\nc"
  後 "  [a\n  b]\nc"
a〜b の改行まで選んで Tab(選択 0〜4)
  前 "[a\nb\n]c"
  後 "  [a\n  b\n]c"
全体を選んで Shift+Tab(選択 0〜14)
  前 "[    a\n  b\n\tc\nd]"
  後 "[  a\nb\nc\nd]"
キャレットが b の後で Shift+Tab(選択 9〜9)
  前 "    a\n  b[]\n\tc\nd"
  後 "    a\nb[]\n\tc\nd"
d の行で Shift+Tab(選択 14〜14)
  前 "    a\n  b\n\tc\nd[]"
  後 null(変更なし)
「  」だけの行で Shift+Tab(選択 2〜2)
  前 "  []"
  後 "[]"

In the case of Tab with the selection running from a through the line break, the selection ends at the start of line c. No character of line c is selected, so that line is not indented. For Shift+Tab, it removes two spaces from the line with four spaces, two spaces from the line with two spaces, and one tab from the line that starts with a tab.

Insert as a browser edit so Ctrl+Z can undo it

I set the textarea's selection to from to to, then insert the computed change with document.execCommand('insertText'). The full component is below.

tsx
import { useState, type KeyboardEvent } from 'react';
import { computeIndent, type IndentEdit } from './indent';

const INITIAL = 'function meow() {\nconsole.log("にゃー");\n}';

// Replace as a browser edit (Ctrl+Z can undo it, and an input event fires)
function applyEdit(el: HTMLTextAreaElement, edit: IndentEdit) {
  el.setSelectionRange(edit.from, edit.to);
  const ok = edit.insert === ''
    ? document.execCommand('delete')
    : document.execCommand('insertText', false, edit.insert);
  if (!ok) {
    // When execCommand is not available (Ctrl+Z cannot undo this)
    el.setRangeText(edit.insert, edit.from, edit.to);
    el.dispatchEvent(new Event('input', { bubbles: true }));
  }
  el.setSelectionRange(edit.selStart, edit.selEnd);
}

export function TabTextarea() {
  const [text, setText] = useState(INITIAL);
  // Only right after Esc, let Tab move focus
  const [tabMovesFocus, setTabMovesFocus] = useState(false);

  function handleKeyDown(e: KeyboardEvent<HTMLTextAreaElement>) {
    if (e.key === 'Escape') {
      setTabMovesFocus(true);
      return;
    }
    if (e.key !== 'Tab' || e.ctrlKey || e.altKey || e.metaKey || tabMovesFocus) {
      // Keys other than Tab, or the Tab right after Esc, are left to the browser
      setTabMovesFocus(false);
      return;
    }
    e.preventDefault(); // do not move focus to the next element
    const el = e.currentTarget;
    const edit = computeIndent(el.value, el.selectionStart, el.selectionEnd, e.shiftKey);
    if (edit) applyEdit(el, edit);
  }

  return (
    <div>
      <label htmlFor="code">コード</label>
      <textarea
        id="code"
        rows={6}
        value={text}
        onChange={(e) => setText(e.target.value)}
        onKeyDown={handleKeyDown}
        onFocus={() => setTabMovesFocus(false)}
        aria-describedby="code-help"
        spellCheck={false}
      />
      <p id="code-help" className="help">
        {tabMovesFocus
          ? '次に Tab を押すと、次の項目へ移ります。'
          : 'Tab で字下げ、Shift+Tab で字下げを戻します。Esc を押してから Tab を押すと、次の項目へ移ります。'}
      </p>
    </div>
  );
}

I pressed Tab twice and Shift+Tab once at the start of line 2, then pressed Ctrl+Z three times. Each Ctrl+Z went back one state.

text
Tab 1回目      値 "function meow() {\n  console.log(\"にゃー\");\n}"   | 選択 20〜20
Tab 2回目      値 "function meow() {\n    console.log(\"にゃー\");\n}" | 選択 22〜22
Shift+Tab      値 "function meow() {\n  console.log(\"にゃー\");\n}"   | 選択 20〜20
Ctrl+Z 1回目   値 "function meow() {\n    console.log(\"にゃー\");\n}" | 選択 18〜41
Ctrl+Z 2回目   値 "function meow() {\n  console.log(\"にゃー\");\n}"   | 選択 20〜20
Ctrl+Z 3回目   値 "function meow() {\nconsole.log(\"にゃー\");\n}"     | 選択 18〜18

When I pressed Tab with the whole text selected, a single Ctrl+Z restored all three lines. This component replaces all touched lines in one insertText call.

The MDN page on execCommand() says the method is deprecated. It also notes that no alternative keeps the editing history. insertText removes the selection and inserts text, and delete removes the selection.

When Shift+Tab makes a line that holds only spaces empty, there is no text to insert, so I use delete. Pressing Shift+Tab on a line with just two half-width spaces empties it, and Ctrl+Z restored the two spaces.

When I insert with insertText, the textarea fires an input event (with inputType set to insertText), and React's onChange runs. After indenting, I pressed Esc to switch the help text, which re-renders the component. The value stayed indented. Since the value was not reverted by the re-render, the state text is updated to match the DOM value.

For comparison, I also built a version that rebuilds the state string from the result of computeIndent, renders it with flushSync, and then restores the selection. Indenting worked, but no input event fired, and Ctrl+Z did not change the value.

text
全体を選んで Tab   値 "  function meow() {\n  console.log(\"にゃー\");\n  }" | 選択 2〜45
  input イベントの inputType: []
Ctrl+Z 1回目       値 "  function meow() {\n  console.log(\"にゃー\");\n  }" | 選択 2〜45

Writing to state breaks Ctrl+Z. I compared this in detail for inserting emoji in my earlier article, "Building an Emoji Picker That Inserts into an Input in React." That article also covers the cautions for using execCommand().

When execCommand() returns false, I replace the text with setRangeText() and fire an input event myself so that onChange runs. I forced execCommand to always return false to test this path. Indenting worked, and the value was kept after a re-render. However, in this case Ctrl+Z did not change the value.

Tab no longer leaves the textarea, so document the exit

If Tab is used for indenting, keyboard-only users cannot leave the textarea with Tab. The WCAG 2.2 explanation of No Keyboard Trap says that a component which cannot be left with the usual methods, such as arrow keys or Tab, still meets the criterion if the user is told how to leave it. It also says that Esc is a common way out in many environments with a physical keyboard. The same explanation gives a rich text editor that indents with Tab and Shift+Tab as an example, with the way out explained.

So I left only the Tab right after Esc unstopped, and let the browser handle it. The way out is written below the textarea and linked to it with aria-describedby. When Esc is pressed, this sentence changes to "Next, press Tab to move to the next item."

text
本文で Tab を3回             選択 45〜45 | フォーカス: 本文
Esc のあと Tab              選択 45〜45 | フォーカス: ボタン「保存」
ボタンから Shift+Tab で本文に戻る  選択 45〜45 | フォーカス: 本文
戻ってから Tab              選択 47〜47 | フォーカス: 本文
Esc、「a」と打ってから Tab     選択 50〜50 | フォーカス: 本文

Pressing Tab three times kept focus in the textarea, and six spaces were added at the end. The Tab after Esc did not change the value, and focus moved to the Save button. Shift+Tab back into the textarea reset tabMovesFocus to false through onFocus, so Tab indents again. Pressing another key such as "a" after Esc also resets it to false, so the Tab that follows indents.

​Posted by 86