1.0.6 • Published 8 months ago
grid-cell-selection v1.0.6
Grid Cell Selection
A React hook for grid cell selection. A simple headless hook that.
Made by Atticus
Installation
npm install grid-cell-selection
Usage
Mouse Only
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 (
<>
<table onMouseUp={handleMouseUp}>
<tbody>
{Array.from({ length: rows }, (_, row) => (
<tr key={row}>
{columns.map((column, col) => (
<td
key={`${row}-${col}`}
onMouseEnter={(event) => handleMouseEnter({ id: `${row}-${col}`, row, col }, event)}
onMouseDown={(event) => handleMouseDown({ id: `${row}-${col}`, row, col }, event)}
className={`${isCellSelected({ id: `${row}-${col}`, row, col }) ? "selected" : ""}`}
>
{column}
{row}
</td>
))}
</tr>
))}
</tbody>
</table>
</>
);
}
Mouse + Touch
Note that data-cell-id, data-cell-row, and data-cell-col are required for touch events to work.
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 (
<table
onMouseUp={handleMouseUp}
onTouchMove={handleTouchMove}
onTouchEnd={handleMouseUp}
style={{ touchAction: "none" }}
>
<tbody>
{Array.from({ length: rows }, (_, row) => (
<tr key={row}>
{columns.map((column, col) => (
<td
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}
</td>
))}
</tr>
))}
</tbody>
</table>
);
}
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
Cell Selection Behavior
Single Cell Selection
- Click on a cell to select it.
- Clicking on a different cell deselects any previously selected cells.
Range Selection
- Click and drag to select a range of cells
Multiple Range Selection
- Hold Ctrl (or Cmd on Mac) or Shift to select multiple ranges
ID Prop
If you provide an array of all cells, the hook will include the cell IDs when tracking the selected cells.