geekskai Logogeekskai
ToolsBlogPricing
Sign in
Sign in
ToolsBlogSign in
Saturday, February 8, 2025|5.965Mins Read

React Editable Tables: Save, Cancel, Validation and Stable Row IDs

Authors
  • avatar
    Name
    Geeks Kai
    Twitter
    @KaiGeeks
Discuss on Twitter • View on GitHub

Tags

reacttablesdata-managementui-componentsweb-development

Previous Article

AI-Powered Direct Exam Prompts: The Lawyer's Secret Weapon for Killer Questions

Next Article

Fix 'chatd cannot find module worker.js' Issue Easily
← Back to the blog
geekskai Logo
geekskai

Public tools for developers and creators, plus optional Geekskai Audio Toolkit plans. Built with care.

Popular Tools

SoundCloud DownloaderSoundCloud to MP3SoundCloud to WAVSoundCloud PlaylistSoundCloud Artwork
View All Tools

Resources

BlogAbout MePricingTagsProjectsPrivacy PolicyTerms of ServiceRefund Policy

Connect With Us

mailMail
githubGitHub
twitterTwitter
linkedinLinkedin
© 2026 geekskai • All rights reserved
React editable table example

An editable table needs more than a table or a virtualized list. I separate the committed rows from the active draft, validate before Save, and use a stable business ID to identify the row. Cancel discards the draft without changing the committed values.

This example uses React 19.3.0 and a native HTML table. It stores changes only in the current browser state. "Saved locally" does not mean a server accepted the change or that another user can see it.

Start with a small working row editor

Use the package.json, index.html, Vite configuration, and src/main.jsx from the fixed React/Vite starter. Keep React/React DOM 19.3.0, Vite 8.2.2, and plugin-react 6.0.4. Replace App.jsx with the table below and add editable-rows.js; no table library is needed for this example.

The rows deliberately have the same name but different IDs. A name or visible array index must not decide which record is changed. Quantities here may be zero, unlike the cart's minimum quantity of one.

src/editable-rows.js

import { useState } from "react"

export const INITIAL_ROWS = [
  { id: "row-a", name: "Pens", quantity: 2 },
  { id: "row-b", name: "Pens", quantity: 5 },
]

export function validateRowDraft(draft) {
  const name = draft.name.trim()
  const quantityText = draft.quantityText.trim()
  const quantity = Number(quantityText)
  if (name === "") {
    return { values: null, error: "Name is required." }
  }
  if (!/^\d+$/.test(quantityText) || !Number.isSafeInteger(quantity) || quantity < 0) {
    return { values: null, error: "Quantity must be a non-negative whole number." }
  }
  return { values: { name, quantity }, error: "" }
}

export function applyRowEdit({ rows, id, values }) {
  return rows.map(row => row.id === id ? { ...row, ...values } : row)
}

export function useEditableRows(initialRows = INITIAL_ROWS) {
  const [rows, setRows] = useState(initialRows)
  const [draft, setDraft] = useState(null)
  const [errorMessage, setErrorMessage] = useState("")
  const [statusMessage, setStatusMessage] = useState("")
  function startEdit(row) {
    setDraft({ id: row.id, name: row.name, quantityText: String(row.quantity) })
    setErrorMessage("")
    setStatusMessage("")
  }
  function changeDraft({ field, value }) {
    setDraft(previousDraft => ({ ...previousDraft, [field]: value }))
    setErrorMessage("")
  }
  function saveEdit() {
    const result = validateRowDraft(draft)
    if (result.error) {
      setErrorMessage(result.error)
      return
    }
    setRows(previousRows => applyRowEdit({ rows: previousRows, id: draft.id, values: result.values }))
    setDraft(null)
    setStatusMessage("Saved locally.")
  }
  function cancelEdit() {
    setDraft(null)
    setErrorMessage("")
    setStatusMessage("Edit cancelled.")
  }
  return { rows, draft, errorMessage, statusMessage, startEdit, changeDraft, saveEdit, cancelEdit }
}

Editing copies values into a draft. Only validated values reach applyRowEdit, and the functional update applies them to the matching ID in the current row array. That keeps the update correct if the array order changes. The ID itself is not editable in this example.

src/App.jsx

import { useEditableRows } from "./editable-rows.js"

function EditableRow({ row, editor }) {
  const isEditing = editor.draft?.id === row.id
  if (isEditing) {
    return (
      <tr data-row-id={row.id}>
        <th scope="row">{row.id}</th>
        <td><label>Name for {row.id}<input value={editor.draft.name}
          onChange={event => editor.changeDraft({ field: "name", value: event.target.value })} /></label></td>
        <td><label>Quantity for {row.id}<input inputMode="numeric" value={editor.draft.quantityText}
          onChange={event => editor.changeDraft({ field: "quantityText", value: event.target.value })} /></label></td>
        <td><button onClick={editor.saveEdit}>Save</button><button onClick={editor.cancelEdit}>Cancel</button></td>
      </tr>
    )
  }
  return (
    <tr data-row-id={row.id}>
      <th scope="row">{row.id}</th><td>{row.name}</td><td>{row.quantity}</td>
      <td><button disabled={editor.draft !== null} onClick={() => editor.startEdit(row)}>Edit {row.id}</button></td>
    </tr>
  )
}

export default function App({ initialRows }) {
  const editor = useEditableRows(initialRows)
  return (
    <main>
      <h1>Editable inventory</h1>
      <table>
        <caption>Save or cancel one local row edit at a time</caption>
        <thead><tr><th scope="col">ID</th><th scope="col">Name</th><th scope="col">Quantity</th><th scope="col">Actions</th></tr></thead>
        <tbody>{editor.rows.map(row => <EditableRow key={row.id} row={row} editor={editor} />)}</tbody>
      </table>
      {editor.errorMessage && <p role="alert">{editor.errorMessage}</p>}
      <p role="status">{editor.statusMessage}</p>
    </main>
  )
}

Use npm run dev for the example and npm run build to check the bundle. The native controls can be reached by keyboard; Tab to Save or Cancel and activate the button. This is a basic row editor, not a spreadsheet keyboard-navigation implementation.

Check the editing contract

ActionExpected result
Edit row-a and type a new namerow-b and the committed row data remain unchanged
Save a non-empty name and quantity 0Only row-a is updated; the editor closes
Save an empty name, empty quantity, negative, fraction, or non-numeric textAn error is shown; no row is committed
Cancel after changing both inputsThe original row is displayed again
Apply a draft by ID to a reordered row arrayThe same business row changes, regardless of its visible position
Two rows share the same nameTheir separate IDs still identify the correct row
Reload the pageThe initial local rows return

For a server-backed editor, keep the draft separate until the write policy is defined. Validation, version/conflict checks, persistence, and handling a removed record are additional requirements; a local state update alone does not implement them.

Choose a library by what it actually supplies

The following options are not a performance ranking. Match the chosen version, editing API, accessibility requirements, and edition to the task. Only the native React example above is implemented here.

OptionEditing boundary
TanStack Table v8Headless table logic; the application supplies inputs and update behavior. Virtualization is separate.
MUI Table / MUI X Data GridBasic Table composition and Data Grid editing APIs are different products; do not attribute every grid feature to the basic Table.
AG GridEditing is configured through the selected version's column/editor APIs; verify modules and edition rather than assuming every feature is included.
React Data GridA data-grid project now hosted under Comcast; use its selected version's editor and row-update contracts.
MUI-DatatablesCustom rendering can host controls, but the application still owns editing and saving behavior.
Semantic UI React TableTable UI composition does not by itself supply a complete editing transaction.
Ant Design TableEditable examples compose Table with Form/input behavior and explicit saving logic.
React Bootstrap Table NextCell editing uses the separate editor package and its configuration.
PrimeReact v10 DataTableThis version's editing uses editor/commit configuration; the archived API is not a promise about every major version.
React VirtualizedList windowing reduces mounted rows; a read-only List is not an editable table implementation.

Do not infer large-dataset speed from a feature list. Measure representative row counts, cell content, editing behavior, and the actual browser before adding windowing or claiming a performance benefit.

Frequently asked questions

Do editable tables require Redux or Zustand? No. Local React state is enough for the example. A shared store may help a particular application's ownership model, but it does not replace validation or a server save contract.

Is this real-time collaboration? No. Other clients do not receive these edits. Multi-user updates need a backend protocol, conflict handling, and a deliberate synchronization strategy.

Can I update by row index after sorting? Prefer stable IDs. The visible index may refer to a different record after sorting or filtering. When using TanStack v8, configure getRowId for the business ID and apply the update to that ID.

References

  • React updating arrays in state
  • React controlled inputs
  • The version-specific library references in the comparison above.