All questions

Selectable Cells

Premium

Selectable Cells

Build a grid where you click and drag to select a rectangular range of cells — like selecting a block in a spreadsheet. The selection is defined by two cells: the anchor (where you pressed down) and the focus (where the pointer is now). A cell is selected when it falls inside the rectangle those two corners span — and using min/max makes dragging in any direction work.

Signature

type Cell = { r: number; c: number };

// A self-contained component. No props.
function App(): JSX.Element;

A grid of cells; press, drag, release to select a rectangle.

Examples

mousedown on (1,1), drag to (3,2), mouseup
  → selects rows 1–3 × cols 1–2  (a 3×2 block, 6 cells)
drag UP-LEFT from (3,3) to (1,1) → still selects the (1,1)–(3,3) block;
min/max means direction doesn't matter.

Notes

  • Anchor + focus. mousedown sets the anchor; dragging (mouseenter while pressed) moves the focus.
  • Rectangle via min/max. Selected when min(r) ≤ r ≤ max(r) and min(c) ≤ c ≤ max(c).
  • End anywhere. Listen for mouseup globally so releasing outside the grid still ends the drag.
  • Derive selection. Don't store a set of cells; compute "in rectangle?" from anchor + focus.

Unlock the solution & editor

  • Runnable editor + tests

    Solve in the browser with instant Jest feedback.

  • Detailed solutions

    Walkthroughs, edge cases, and complexity notes.

  • Multi-framework variants

    React, Vue, Vanilla, Angular — same question, different stacks.

Upgrade to Premium