日本語

Making Table Cells Editable in React

​​React​Accessibility,Playwright,TypeScript

If a table cell is a button normally and an input while being edited, you can rewrite values right in the table. Enter saves, Escape cancels, and clicking outside the input also saves.

However, a simple version that shows an input and saves on Enter has problems. The Enter that confirms a Japanese IME conversion ends editing, and after saving, focus has nowhere to go. Here I build an EditableCell component that fixes these points and compare it with a version that handles none of them.

Note

Test environment: Ubuntu 24.04, Node.js 22.22.0, 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 files with tsc, transpiled them with esbuild, and tested by operating Chromium with Playwright. Japanese IME conversion was reproduced not with a real IME but with Chrome DevTools Protocol (CDP) commands. Even with the development build under StrictMode, the output was the same as the production build, and no errors or warnings appeared in the console. I did not test Firefox, Safari, or screen reader announcements.

Clicking the cell labeled "Mike's age" (the label is in Japanese) turns it into an input with 3 selected. Typing 4 and pressing Enter saves 4. Next, abc is typed into the "Kuro's age" (the label is in Japanese) cell and Enter shows an error. The input stays, and Escape restores the original 7
Editing a cell by clicking it and saving with Enter, then cancelling an invalid value with Escape. A changed cell is highlighted pink only at the moment it is saved or cancelled. The pink border and message on the input during an error are the table’s own styling. The top bar, cursor, and click ripple are overlays added for the GIF

Each cell switches between display mode and edit mode

This is the EditableCell component, which handles one cell. Its editing state and the input's contents are held in a single state, draft. If it is null, the cell is in display mode; if it is a string, the cell is in edit mode.

tsx
import { useEffect, useId, useRef, useState } from 'react';

type Props = {
  value: string;
  label: string; // the input's name, such as "Mike's age"
  validate?: (draft: string) => string | null; // returns a message if there is a problem
  onCommit: (draft: string) => void;
};

export function EditableCell({ value, label, validate, onCommit }: Props) {
  // null means display mode; a string means edit mode (the input's contents)
  const [draft, setDraft] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const buttonRef = useRef<HTMLButtonElement>(null);
  const focusCell = useRef(false);
  const errorId = useId();

  // After editing ends, return focus to the cell only when it ended with Enter or Escape
  useEffect(() => {
    if (draft === null && focusCell.current) {
      focusCell.current = false;
      buttonRef.current?.focus();
    }
  }, [draft]);

  const close = (refocus: boolean) => {
    focusCell.current = refocus;
    setError(null);
    setDraft(null);
  };
  const save = (refocus: boolean) => {
    if (draft === null) return;
    const message = validate?.(draft) ?? null;
    if (message) {
      setError(message);
      return;
    }
    if (draft !== value) onCommit(draft);
    close(refocus);
  };

  if (draft === null) {
    return (
      <button ref={buttonRef} type="button" className="cell" aria-label={`${label} ${value}`} onClick={() => setDraft(value)}>
        {value}
      </button>
    );
  }
  return (
    <>
      <input
        autoFocus
        value={draft}
        aria-label={label}
        aria-invalid={error !== null}
        aria-describedby={error ? errorId : undefined}
        onFocus={(e) => e.currentTarget.select()}
        onChange={(e) => {
          setDraft(e.target.value);
          setError(null);
        }}
        onKeyDown={(e) => {
          // Do not save on the Enter that confirms a Japanese IME conversion
          if (e.key === 'Enter' && !e.nativeEvent.isComposing) {
            e.preventDefault();
            save(true);
          } else if (e.key === 'Escape') {
            e.preventDefault();
            close(true);
          }
        }}
        onBlur={() => save(false)}
      />
      {error && <span id={errorId} className="error">{error}</span>}
    </>
  );
}

I made the display-mode cell a <button> so it can be reached with the Tab key and activated with Enter. Whether by click or keyboard, onClick puts the current value into draft, which switches the cell to edit mode.

EditableCell holds only the string being edited. It does not hold the table's data itself. When saving, it passes the value to the parent with onCommit. If the value has not changed, onCommit is not called.

Keep the table data as an array of rows in the parent

The component that draws the table holds an array of rows in state. In onCommit, it uses map to build a new array in which only the matching row is replaced. This follows React's official documentation on updating objects inside arrays. The __commits line is there to count how many times saving was called.

tsx
const validateName = (draft: string) => (draft.trim() === '' ? '名前を入力してください' : null);
const validateAge = (draft: string) => {
  const s = draft.normalize('NFKC').trim();
  return /^\d+$/.test(s) && Number(s) <= 30 ? null : '0〜30の整数で入力してください';
};

export function CatTable({ naive = false }: { naive?: boolean }) {
  const [cats, setCats] = useState(initialCats);
  const update = (id: number, patch: Partial<Cat>) => {
    // Count how many times save was called, for checking
    (window as any).__commits = ((window as any).__commits ?? 0) + 1;
    setCats((prev) => prev.map((c) => (c.id === id ? { ...c, ...patch } : c)));
  };

Each row has two cells, one for the name and one for the age. For each cell, I pass a validation function (validate) and a function that converts the string into row data (onCommit).

tsx
            <tr key={cat.id}>
              <td>
                <EditableCell value={cat.name} label={`${cat.name}の名前`} validate={validateName}
                  onCommit={(v) => update(cat.id, { name: v.trim() })} />
              </td>
              <td>
                <EditableCell value={String(cat.age)} label={`${cat.name}の年齢`} validate={validateAge}
                  onCommit={(v) => update(cat.id, { age: Number(v.normalize('NFKC').trim()) })} />
              </td>
            </tr>

I omitted the definition of the Cat type (id, name, age) and the initial three rows, initialCats. The naive flag in CatTable switches to the version compared below.

What happens without any handling

For comparison, I prepared NaiveCell. It handles only Enter, Escape, and blur while the input is shown, with no other handling.

tsx
import { useState } from 'react';

// Comparison version: no check for Enter during IME composition, and no focus restoration
export function NaiveCell({ value, label, onCommit }: { value: string; label: string; onCommit: (draft: string) => void }) {
  const [draft, setDraft] = useState<string | null>(null);

  if (draft === null) {
    return (
      <button type="button" className="cell" aria-label={`${label} ${value}`} onClick={() => setDraft(value)}>
        {value}
      </button>
    );
  }
  return (
    <input
      autoFocus
      value={draft}
      aria-label={label}
      onChange={(e) => setDraft(e.target.value)}
      onKeyDown={(e) => {
        if (e.key === 'Enter') {
          onCommit(draft);
          setDraft(null);
        } else if (e.key === 'Escape') {
          setDraft(null);
        }
      }}
      onBlur={() => {
        onCommit(draft);
        setDraft(null);
      }}
    />
  );
}

I performed the same operations on both versions. Each row shows the name and then the age; [ ] marks the input and its contents. 選択 0-1 gives the start and end of the selected range inside the input, counted from 0. 0-1 means the first character is selected. Equal numbers such as 2-2 mean nothing is selected and the caret is at that position. First, EditableCell:

text
開いた直後: ミケ 3 / クロ 7 / シロ 1 | フォーカス: body | 保存 0回
「ミケの年齢」のセルをクリック: ミケ [3] / クロ 7 / シロ 1 | フォーカス: input「ミケの年齢」 選択 0-1 | 保存 0回
「4」と入力: ミケ [4] / クロ 7 / シロ 1 | フォーカス: input「ミケの年齢」 選択 1-1 | 保存 0回
Enter: ミケ 4 / クロ 7 / シロ 1 | フォーカス: button「ミケの年齢 4」 | 保存 1回
「クロの名前」をクリックして「クロスケ」と入力: ミケ 4 / [クロスケ] 7 / シロ 1 | フォーカス: input「クロの名前」 選択 4-4 | 保存 1回
Escape: ミケ 4 / クロ 7 / シロ 1 | フォーカス: button「クロの名前 クロ」 | 保存 1回
「シロの名前」に「ユキ」と入力して、表の外をクリック: ミケ 4 / クロ 7 / ユキ 1 | フォーカス: body | 保存 2回
Tab で先頭のセルに移り Enter: [ミケ] 4 / クロ 7 / ユキ 1 | フォーカス: input「ミケの名前」 選択 0-2 | 保存 2回
「とら」を「トラ」に変換して Enter で確定(CDP で再現): [トラ] 4 / クロ 7 / ユキ 1 | フォーカス: input「ミケの名前」 選択 2-2 | 保存 2回
もう一度 Enter: トラ 4 / クロ 7 / ユキ 1 | フォーカス: button「トラの名前 トラ」 | 保存 3回

Next, NaiveCell:

text
開いた直後: ミケ 3 / クロ 7 / シロ 1 | フォーカス: body | 保存 0回
「ミケの年齢」のセルをクリック: ミケ [3] / クロ 7 / シロ 1 | フォーカス: input「ミケの年齢」 選択 1-1 | 保存 0回
「4」と入力: ミケ [34] / クロ 7 / シロ 1 | フォーカス: input「ミケの年齢」 選択 2-2 | 保存 0回
Enter: ミケ 34 / クロ 7 / シロ 1 | フォーカス: body | 保存 1回
「クロの名前」をクリックして「クロスケ」と入力: ミケ 34 / [クロクロスケ] 7 / シロ 1 | フォーカス: input「クロの名前」 選択 6-6 | 保存 1回
Escape: ミケ 34 / クロ 7 / シロ 1 | フォーカス: body | 保存 1回
「シロの名前」に「ユキ」と入力して、表の外をクリック: ミケ 34 / クロ 7 / シロユキ 1 | フォーカス: body | 保存 2回
Tab で先頭のセルに移り Enter: [ミケ] 34 / クロ 7 / シロユキ 1 | フォーカス: input「ミケの名前」 選択 2-2 | 保存 2回
「とら」を「トラ」に変換して Enter で確定(CDP で再現): トラ 34 / クロ 7 / シロユキ 1 | フォーカス: body | 保存 3回
もう一度 Enter: トラ 34 / クロ 7 / シロユキ 1 | フォーカス: body | 保存 3回

There are three differences.

Select all text in the input when it opens

With NaiveCell, the caret was at the end of the text when the input appeared, so typing "4" produced "34". When you want to rewrite a value, you have to delete the old one every time.

EditableCell calls select() when the input receives focus. As described in MDN's documentation for select(), all the text in the input becomes selected, so typed characters replace it.

After Enter or Escape, return focus to the cell

With NaiveCell, when Enter or Escape removed the input, focus moved to body. No cell had focus, so keyboard users could not tell from the screen which cell they were on.

With EditableCell, when editing ends with Enter or Escape, focusCell is set to true. After the cell returns to display mode, the useEffect moves focus to the button. The button is newly created to replace the input, so focus cannot be moved yet inside the function that ends editing. It is moved in useEffect after rendering finishes.

When editing ends by clicking outside the table, focus is not returned. The click is meant to move focus to where the user clicked, so pulling focus back to the cell would get in the way.

Do not save on the Enter that confirms an IME conversion

In Japanese input, Enter is also used to confirm a conversion. With NaiveCell, the Enter that confirmed the conversion from hiragana "tora" to katakana "tora" ended editing, and nothing could be typed after the katakana.

According to MDN's documentation for isComposing, isComposing on a keyboard event indicates whether the event happened between the start (compositionstart) and the end (compositionend) of an IME composition. EditableCell ignores Enter when isComposing is true on the React event's nativeEvent, which is the browser's original event. So the Enter that confirms a conversion does not save, and saving happens on the next Enter.

When the value is invalid, keep the user editing

When validate returns a message, the input stays open and nothing is saved. The input gets aria-invalid, and the message is linked to it with aria-describedby. MDN's documentation for aria-invalid says that when you write your own validation, you should not only set aria-invalid but also convey through a message what is wrong. MDN lists aria-errormessage as the attribute for linking the message, but here I used aria-describedby.

text
「ミケの年齢」に「abc」と入力して Enter: ミケ [abc](aria-invalid)「0〜30の整数で入力してください」 / クロ 7 / シロ 1 | フォーカス: input「ミケの年齢」 選択 3-3 | 保存 0回
Backspace: ミケ [ab] / クロ 7 / シロ 1 | フォーカス: input「ミケの年齢」 選択 2-2 | 保存 0回
「31」に打ち直して Enter: ミケ [31](aria-invalid)「0〜30の整数で入力してください」 / クロ 7 / シロ 1 | フォーカス: input「ミケの年齢」 選択 2-2 | 保存 0回
表の外をクリック: ミケ [31](aria-invalid)「0〜30の整数で入力してください」 / クロ 7 / シロ 1 | フォーカス: body | 保存 0回
入力欄に戻り、全角の「5」に打ち直して Enter: ミケ 5 / クロ 7 / シロ 1 | フォーカス: button「ミケの年齢 5」 | 保存 1回
「クロの名前」を空にして Enter: ミケ 5 / [](aria-invalid)「名前を入力してください」 7 / シロ 1 | フォーカス: input「クロの名前」 選択 0-0 | 保存 1回
Escape: ミケ 5 / クロ 7 / シロ 1 | フォーカス: button「クロの名前 クロ」 | 保存 1回

When the text is retyped, onChange clears the message. When you click outside the table while the value is still invalid, nothing is saved, and the input and message remain. To give up, press Escape to restore the original value.

For age, I convert full-width digits to half-width with normalize('NFKC') before checking, so full-width digits are also accepted. Here are the results of passing several values to validateAge:

text
"5"     → "5"    OK
"5"     → "5"    OK
" 12 "  → "12"   OK
"12"    → "12"   OK
"30"    → "30"   OK
"31"    → "31"   0〜30の整数で入力してください
"-1"    → "-1"   0〜30の整数で入力してください
"2.5"   → "2.5"  0〜30の整数で入力してください
"abc"   → "abc"  0〜30の整数で入力してください
""      → ""     0〜30の整数で入力してください

The onBlur of the input removed by Escape was not called

EditableCell also saves in the input's onBlur. That raises a concern: when Escape removes the input, focus leaves the disappearing input, which could call onBlur and save the value that was supposed to be cancelled.

To check this, I attached handlers directly to the input before pressing Escape. They count the blur and focusout events. The first line is EditableCell, and the ?naive line is NaiveCell.

text
EditableCell: 入力欄に届いたイベント ["blur","focusout"] / 入力欄の数 0 / 保存 0回
?naive: 入力欄に届いたイベント ["blur","focusout"] / 入力欄の数 0 / 保存 0回

In Chromium 153, blur and focusout fired when the input was removed. Even so, the save count stayed at 0. NaiveCell's onBlur always calls onCommit, so the onBlur of a removed input was not called in React 19.3.1.

EditableCell relies on this behavior. If an environment did call the onBlur of a removed input, the value cancelled with Escape would be saved. In this environment, the value cancelled with Escape was not saved, and each save with Enter increased the save count by exactly one.

​Posted by 86