A React hook for grid cell selection
npm install grid-cell-selectionA React hook for grid cell selection. A simple headless hook that.
``bash`
npm install grid-cell-selection
`tsx
import React from "react";
import { useGridCellSelection } from "grid-cell-selection";
function App() {
const columns = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"];
const rows = 20;
const { isCellSelected, handleMouseDown, handleMouseEnter, handleMouseUp } = useGridCellSelection();
return (
<>
| key={${row}-${col} |
$3
> Note that data-cell-id, data-cell-row, and data-cell-col are required for touch events to work.
`tsx
function App() {
const columns = ["A", "B", "C", "D", "E", "F", "G"];
const rows = 100; const { isCellSelected, handleMouseDown, handleMouseEnter, handleMouseUp, handleTouchMove, handleTouchStart } =
useGridCellSelection({
options: { allowYScrollSelection: true, clearSelectionOnScroll: true, scrollThreshold: 100 },
});
return (
onMouseUp={handleMouseUp}
onTouchMove={handleTouchMove}
onTouchEnd={handleMouseUp}
style={{ touchAction: "none" }}
>
{Array.from({ length: rows }, (_, row) => (
{columns.map((column, col) => (
key={${row}-${col}}
onMouseEnter={(event) => handleMouseEnter({ id: ${row}-${col}, row, col }, event)}
onMouseDown={(event) => handleMouseDown({ id: ${row}-${col}, row, col }, event)}
onTouchStart={(event) => handleTouchStart({ id: ${row}-${col}, row, col }, event)}
className={${isCellSelected({ id: ${row}-${col}, row, col }) ? "selected" : ""}}
data-cell-id={${row}-${col}} // Required for touch events
data-cell-row={row} // Required for touch events
data-cell-col={col} // Required for touch events
>
{column}
{row}
))}
))}
);
}
``
Options:
- allowYScrollSelection: boolean - Whether to allow vertical scrolling selection
- clearSelectionOnScroll: boolean - Whether to clear the selection when the user scrolls
- scrollThreshold: number - The number of pixels the user must scroll before the selection is cleared
``- Click on a cell to select it.
- Clicking on a different cell deselects any previously selected cells.
- Click and drag to select a range of cells
- Hold Ctrl (or Cmd on Mac) or Shift to select multiple ranges
If you provide an array of all cells, the hook will include the cell IDs when tracking the selected cells.