Repository navigation
Replies: 1 comment
|
When managing a dynamic 2D grid in form state (where both rows and columns can be added, removed, or reordered), the standard nested array model ( In TanStack Form, arrays are managed via array helpers (
Below is the idiomatic, high-performance architecture for handling 2D grids in TanStack Form. Recommended Architecture: Decouple Grid Structure from Cell ValuesInstead of treating the grid as a 2D matrix of arrays, separate the topology (the ordered list of rows and columns) from the cell storage (a normalized dictionary keyed by stable IDs): interface Widget {
id: string;
name: string;
}
interface Location {
id: string;
name: string;
}
interface GridFormValues {
rows: Widget[]; // Controls row order & metadata
columns: Location[]; // Controls column order & metadata
cells: Record<string, string>; // Keyed by `${widgetId}:${locationId}`
}Why this solves every problem:
Complete Reproducible Example (
|
| Feature | Normalized Compound Map (cells['row:col']) |
Row-Grouped Dictionary (rows[r].values[col]) |
|---|---|---|
| Row swap/reorder | form.swapFieldValues('rows', a, b) preserves cell values without copying. |
form.swapFieldValues('rows', a, b) automatically moves row cell values with the row. |
| Column swap/reorder | form.swapFieldValues('columns', a, b) instantly updates rendering with zero cell updates. |
form.swapFieldValues('columns', a, b) instantly updates rendering with zero cell updates. |
| Deleting a row | Remove from rows; cells can be pruned at submit time. |
Automatically deletes the row's values map. |
| Performance | Maximum granularity; cell paths are globally independent. | High granularity scoped to the row path. |
Both avoid the sparse array issue entirely while keeping column additions and reordering an
Uh oh!
There was an error while loading. Please reload this page.
I have a 2D grid of information. I have locations which make up "columns" and widgets which make up "rows". Every column needs an input within the column. My naive solution was to Subscribe to locations in the row, and then display an input for each column.
Making the row an array of inputs doesn't work because it treats the inputs as sparse, due to not calling
pushValueon each row's array when adding a new column. I could potentially manage this using listeners, especially if I had the previous value. This is significantly more difficult for swapValue, etc.I'd be curious to hear solutions for this!
All reactions