0 day streak
javascript / intermediate
Snippet

Managing Dynamic Grid Inputs with Curried Event Handler Functions

Currying event handler functions allows pre-binding dynamic grid coordinates (row and column indices) in closure scope while returning a standard event handler. Inside the updater, nested Array.map calls enforce immutable state updates without mutating the 2D matrix in place.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import React, { useState } from 'react';
export function MatrixEditor({ rows, cols }) {
const [grid, setGrid] = useState(() =>
Array.from({ length: rows }, () => Array(cols).fill(''))
);
const handleCellChange = (rowIndex, colIndex) => (event) => {
const nextValue = event.target.value;
setGrid((prevGrid) =>
prevGrid.map((row, r) =>
r === rowIndex
? row.map((cell, c) => (c === colIndex ? nextValue : cell))
: row
)
);
};
return (
<div className="matrix-grid">
{grid.map((row, r) => (
<div key={r} className="matrix-row">
{row.map((val, c) => (
<input
key={`${r}-${c}`}
value={val}
onChange={handleCellChange(r, c)}
/>
))}
</div>
))}
</div>
);
}
react
Breakdown
1
const handleCellChange = (rowIndex, colIndex) => (event) => {
Creates a higher-order curried function capturing the target coordinates in closure scope.
2
prevGrid.map((row, r) => r === rowIndex ? row.map(...) : row)
Performs an immutable update across the multi-dimensional array by mapping only the modified index.
3
onChange={handleCellChange(r, c)}
Invokes the outer curried function during render, supplying the exact row and column listener.