Entry row
Show an entry row at the end of the table with newRow and add typed rows to the end. Drafts, when it becomes a row, paste, and tracking added and removed rows
With newRow, an empty entry row appears at the end of the table, and typing there adds a row (since 1.10.0; like the last row of an Excel table or Airtable). The grid holds the entry row, so unlike the old approach of keeping an empty row in rows, no empty row gets mixed into sorting, counts, validation or export.
Demo (order lines > add rows and save)
(Type in the entry row to add a row, then press Save; what was sent shows up here)
- Start typing in the Code cell of the last row (its row number is "*"), or start editing with
F2/ double-click. Writing a value makes it a draft, and the row number changes to "✎". - Commit with
Enterand the row is added at the end, moving to the same column of the next entry row. While you move right withTab, it stays a draft;Tabin the last column, moving to another row, or clicking outside the grid makes it a row. - Pressing
Escapeon a draft (when not editing) discards the draft. - Pasting two or more rows into the Code column adds as many rows as were pasted.
Ctrl+Z(⌘Zon Mac) removes the added row in one step.- This demo also has
trackChanges={{ rows: true }}. Added rows get a vertical line left of the row number, and the bottom bar shows "1 row added". Select rows and press "Delete the selected rows" to count them as removed; "Save" logs what was sent ("Saving added and removed rows" below).
Usage
import { useState } from 'react';
import { SpreadsheetGrid, type GridColumn } from '@ishibashi0112/spreadsheet-grid';
type Item = { id: string; name: string; qty: number | null };
const columns: GridColumn<Item>[] = [
{ key: 'name', title: 'Item', width: 200, editable: true },
{ key: 'qty', title: 'Qty', width: 100, editable: true, editor: { type: 'number' } },
];
const [rows, setRows] = useState<Item[]>(initialRows);
<SpreadsheetGrid
rows={rows}
onRowsChange={setRows}
columns={columns}
rowKeyGetter={(row) => row.id}
createRow={() => ({ id: crypto.randomUUID(), name: '', qty: null })}
newRow
/>;- The entry row appears when rows are passed with
rowsandonRowsChange, there arecreateRowandrowKeyGetter, and the grid isn'treadOnly. If something is missing, it doesn't appear, and a warning shows once in development. - It doesn't appear with serverSide (
dataSource) or while grouping rows (rowGroup) (server rows are refetched after saving / it wouldn't be decided which group an added row joins). - The entry row is always the last row, even while sorted or filtered. Added rows are ordinary rows, so they sort into place and disappear if they don't match the filter.
Text of the empty entry row (placeholder)
The empty entry row shows "Type here to add a row" in faint text in the first editable column.
<SpreadsheetGrid {...props} newRow={{ placeholder: 'Type an item to add it' }} /> // text in the first editable column
<SpreadsheetGrid {...props} newRow={{ placeholder: (column) => (column.key === 'qty' ? '0' : null) }} /> // per column
<SpreadsheetGrid {...props} newRow={{ placeholder: '' }} /> // noneThe default text is newRowPlaceholder in localeText; to change it per table, use placeholder. The spoken names of the row number are newRowHeader ("New row") and newRowDraftHeader ("New row (draft)").
When createRow is called
createRow may have side effects like numbering, so just drawing the empty entry row doesn't call it. It's called once, when editing first starts in the entry row, and that row is kept as the base of the draft. Closing without writing anything doesn't discard it; it's reused the next time.
- Draft cells are drawn with the draft row, so
ctx.rowKeyinrenderCell/cellClassName/getRowClassNameis therowKeyGettervalue of the draft row (ctx.sourceRowIndexis-1). It keeps the same key after becoming a row. - Functions for the select editor's per-row
optionsandcanEditCellalso receive this row. - On the empty entry row before a value is written, your functions (
renderCell/cellClassName/cellNote/getRowClassName/validate/ conditional formatting) aren't called.
When it becomes a row, and when it's dropped
| Action | What happens |
|---|---|
Enter in a draft's editor | Becomes a row and moves to the same column of the next entry row (stays a draft when editorEnterMove isn't 'down') |
Tab in the last column of a draft (editing or not. The column before it when no editable column is to the right = when a read-only column such as a numbering column is last) | Becomes a row and moves to the first editable column of the next entry row |
| The active cell moves to another row | Becomes a row |
| Focus leaves the grid (including the top / bottom bars) | Becomes a row. When pressing outside, at the moment of release (before that click) |
The entry row stops applying (switching to readOnly, removing createRow and so on) | Becomes a row |
Undo / redo (Ctrl+Z / Ctrl+Y) | Becomes a row first (undo removes that row, redo brings it back) |
The handle's commitNewRow() | Becomes a row ("Making it a row before saving" below) |
Escape on an entry row that isn't being edited | Discards the draft (nothing reaches your app. Can't be undone) |
Unmounting the grid with a draft (switching tabs, hiding with Solid's <Show> and so on) | Discarded (onRowsChange isn't called). To keep it, call commitNewRow() before unmounting |
- Becoming a row calls
onRowsChangeonce with an array that has one row added to the end ofrows. One undo (Ctrl+Z) removes it. Cell edits during the draft aren't recorded in the undo history. - Committing it empty (
F2→Enter, for example) doesn't make a draft. When all values are cleared and it's back to thecreateRowrow (Deleteand so on; empty =null/undefined/''are treated the same), it goes back to an empty entry row and moving to another row doesn't add it. - Opening the column menu (
Alt+↓) or a filter during a draft doesn't make it a row (while a popup is open, it doesn't count as leaving). - When pressing outside the grid makes it a row and the table was scrolled to the end, it stays at the end after adding (the entry row doesn't hide below the table's bottom edge or behind the total row).
Tabin the last column of an empty entry row leaves the grid (so the keyboard isn't trapped).Ctrl+Enter(excelShortcuts) on the entry row commits without moving, so it stays a draft.- Validation (
validate) applies to draft cells too. They go intogetInvalidCells()once they become a row.
Making it a row before saving (commitNewRow)
Drafts aren't in getChanges(). When a "Save" button outside the grid is pressed, the draft becomes a row on release, so it's in the getChanges() read in the button's onClick. When saving with focus still in the grid (a key such as Ctrl+S), call the handle's commitNewRow() first. If the entry row is being edited, it commits the editor and then makes the row (true if it made a row).
window.addEventListener('keydown', (event) => {
if ((event.ctrlKey || event.metaKey) && event.key === 's') {
event.preventDefault();
gridRef.current?.commitNewRow();
save(gridRef.current?.getChanges());
}
});Receiving whether there is a draft (onDraftChange)
If your save button is disabled by the unsaved count, it can't be pressed when there is only a draft (drafts aren't counted). Receive whether there is a draft with newRow.onDraftChange and include it in the condition. After rendering, it passes the draft row (a value was written) or null (it became a row, was discarded, or went back to empty). It also works for a confirmation before leaving the page.
const [hasDraft, setHasDraft] = useState(false);
<SpreadsheetGrid {...props} newRow={{ onDraftChange: (draft) => setHasDraft(draft !== null) }} />;
<button disabled={unsaved === 0 && !hasDraft} onClick={save}>Save</button>;Pressing the button makes the draft a row on release, so it's in getChanges() in onClick.
Paste and selection
- Pasting from the entry row makes rows right away, as many as were pasted (the first is the entry row's row, the rest are rows made with
createRow; oneonRowsChange). It's the same as a paste that spills past the end. - Only the active cell can be on the entry row. Range selection, select all (
Ctrl+A), row and column selection, row checkboxes, the fill handle and row drag don't include the entry row (a range stretched from a data row to the entry row ends at the last data row). Ctrl+End/Ctrl+↓stop at the last data row. Move to the entry row with↓orfocusNewRow().- It isn't included in counts, selection aggregates, the total row, copy, find or export either. The total row and bottom pinned rows stay below the entry row. The spoken row count (
aria-rowcount) includes the entry row. - The entry row doesn't open the context menu and doesn't call
onCellClick/onCellDoubleClick. excelShortcuts'sCtrl+Dwrites the value of the data row above,Ctrl+Rthe value of the column to the left, andCtrl+;today's date into the draft (it becomes a row when you leave the row).- The empty entry row comes before
createRowis called, so checkbox columns draw nothing either (the default value of the row to be made isn't known). Toggle withSpace, or type in another column to make a draft, and it's drawn. - Pasting a cut range into the entry row moves the rows (the pasted rows are added rows, the originals are emptied rows). Rows cut whole (
Shift+Space) are pasted from the column of the entry row's active cell. To move a row's values as they are, move to the first column of the entry row before pasting.
Going to the entry row with the keyboard (focusNewRow)
The handle's focusNewRow() moves to the first editable cell of the entry row, scrolls it into view and moves focus to the grid (true if it could). Use it for an "Add row" button that moves to the entry row.
<button onClick={() => gridRef.current?.focusNewRow()}>Add row</button>Saving added and removed rows
Add trackChanges={{ rows: true }} of change tracking and rows added in the entry row are counted as "added". They're in added of getChanges(), so you know which rows to insert when saving.
const changes = grid.getChanges();
await api.save({
insert: changes.added?.map(({ row }) => row) ?? [],
update: changes.rows.map(({ rowKey, row, columnKeys }) => ({ id: rowKey, columnKeys, row })),
delete: changes.removed?.map(({ rowKey }) => rowKey) ?? [],
});
grid.markChangesSaved(changes);Drafts in the entry row aren't counted (they're counted once they become rows). Details are in "Tracking added and removed rows too" in Change tracking.
With other features
- Tree data (
treeData): the parent of an added row is decided bygetParentKeyof the rowcreateRowreturns (createRowtakes no arguments, so to add under the selected row, remember the selected row in your app and read it insidecreateRow). Rows added under a closed parent disappear right after being added (the parent's row number shows the unsaved dot). The entry row is outside the tree and has noaria-level. - Your own key handling: if a table that handled
Ctrl+D/Ctrl+Xand the like itself up to 1.9 getsexcelShortcuts(or even without it, forCtrl+X), both the grid and your handling run. Keys the grid handled haveevent.defaultPreventedset totrue, so stop your handling when you see it, or remove your handling.
Moving from the "empty last row" of 1.9 and earlier
Tables that kept adding an empty row at the end inside onRowsChange should remove that logic before adding newRow. If it stays, empty rows remain in the middle, every added empty row clears the undo history (it counts as replacing rows from outside), and rows typed into the empty row are counted as "unsaved cells" rather than "added", so they're missing from added when saving.
Look
- Entry row cells have a background with a little of the accent color mixed in, and the row number marks (* / ✎) are in the accent color.
- The row gets
.ssg-body-row--newanddata-ssg-new-row("empty"/"draft"), the row number gets.ssg-row-header-cell--new, and the text of the empty entry row gets.ssg-new-row-placeholder(its color is--ssg-readonly-textmoved a little toward the body text color). - The text of the empty entry row appears only in the first editable column, so it gets cut off when that column is narrow. To show short text per column, pass a function to
placeholder.
/* remove the entry row's background */
.ssg-body-row--new > .ssg-body-cell {
background-color: var(--ssg-cell-bg);
}With /lite
With /lite, add the feature part newRowFeature (it isn't in standardFeatures).
import { createSpreadsheetGrid, newRowFeature } from '@ishibashi0112/spreadsheet-grid/lite';
const Grid = createSpreadsheetGrid({ features: { newRow: newRowFeature } });Adding newRow in a setup without it shows no entry row, with one warning in development.
Cell editing
Editor types (text / number / select / date / time / datetime / checkbox / custom), per-row editors, values with line breaks, where to move after committing, editing from code, and an overview of validation
Searchable select editor
Narrow options by typing with the select editor's search (also by reading or alias, options fetched from a server, filling other columns from the chosen option)