Vibe coding with Claude Code course Β· Module 14: Pinterest clone
A Treasure Map in Columns: A Masonry Grid from a Sketch
In this lesson12
Ahoy! In this location you build Treasure Map, a Pinterest clone: a service where people pin inspiring pictures to boards. One picture with a title and an author is a pin. The trouble starts on the home page. The photos have different heights, and a plain grid lays them out in rows as tall as the tallest photo, so gaps are left under the shorter ones. A masonry layout (like a brick wall) has columns, and each next pin goes into the column that is the shortest at that moment. Like a quartermaster who always puts a new crate on the lowest stack.
What you will learn
- give Claude a sketch of the layout and check that it read it the way you did;
- read the shortest-column algorithm and spot state that is set during render;
- pick the number of columns for the window width without a hydration error;
- reserve space for an image before it downloads and keep the keyboard focus in order;
- order infinite scrolling with a sentinel, without double requests.
A new port: the treasure-map project
The clone is a separate app, so you create it with the command from lesson 1_2, changing only the name:
npx create-next-app@latest treasure-map --ts --eslint --tailwind --app --no-src-dir --no-cache-components --agents-md --no-agent-feedback --use-npmThen the familiar routine: a claude session, a CLAUDE.md that imports @AGENTS.md (lesson 1_7), Vitest with the @types/node fix from lesson 4_1, and a first commit. Put a dozen or so photos 600 pixels wide and of different heights into public/pins/: your own, or coloured test cards from ffmpeg, as in lesson 12_1. Images from the project do not need a remotePatterns entry from lesson 3_1.
A sketch instead of a description
A column layout is easier to draw than to describe. Draw four columns of rectangles of different heights on a sheet of paper and save the photo as sketches/masonry.png. You hand it over by file path, as in lesson 3_2. A sketch shows the look, not the behaviour: the number of columns on a phone and what the Tab key does must be written in the text of the request.
Request for Claude Code
This change touches data, a function, three components and a page, so you start with a plan, as in lesson 1_6:
Request for Claude Code:
/plan First describe what you see in the sketch sketches/masonry.png.
Then plan the Treasure Map home page: a masonry grid of the pins from
lib/pins.ts (images from public/pins, each pin has width, height and
dominantColor). Each pin goes into the shortest column; compute the
split in a pure function in lib/masonry.ts, not in state. Columns: 2
on a phone, 3 from 768 px, 4 from 1024 px, with no hydration error.
Space for the image reserved before it downloads, background in the
dominant colour. Pin card: a Save button in the top right corner,
title and author at the bottom, visible on mouse hover and on
keyboard focus. Tests for lib/masonry.ts first. Done when
npm run test -- --run, npm run lint and npx tsc --noEmit pass
without errors.In the plan, read the description of the sketch and check that the split is a pure function and where Claude will get the window width from. If the plan is silent about it, correct it with Ctrl+G.
What Claude wrote: pin data
Open lib/types.ts in Cursor. A pin has only the fields this lesson uses:
// lib/types.ts
export interface Pin {
id: string;
title: string;
author: string;
src: string;
width: number;
height: number;
dominantColor: string; // "#rrggbb"
tags: string[];
}width and height are the dimensions of the file in pixels, not the size on the screen. dominantColor is the colour that takes up most of the photo, calculated once, when the file is added. The tags will be useful in lesson 13_3.
What Claude wrote: the shortest column
Open lib/masonry.ts. The whole algorithm is one loop that takes the pins one by one and adds each to the column that is the shortest at that moment:
// lib/masonry.ts
export function distributePins<T extends Sized>(pins: readonly T[], columnCount: number): T[][] {
const columns: T[][] = Array.from({ length: columnCount }, () => []);
const heights: number[] = new Array(columnCount).fill(0);
for (const pin of pins) {
const shortest = heights.indexOf(Math.min(...heights));
columns[shortest].push(pin);
heights[shortest] += pin.height / pin.width; // height when the column width is 1
}
return columns;
}Sized is a type from this file: anything that has width and height. Math.min(...heights) finds the lowest height and indexOf finds the number of its column; on a tie the column on the left wins. The columns have equal width, so the last line adds just the ratio height / width: there is no need to know the pixels on the screen. The function does not change the input array, it only builds new ones.
Of the five tests, remember one: "adding pins does not move earlier ones". The loop goes through the pins in order, so when further pages are loaded, nothing jumps in front of the viewer's eyes. Our result: Tests 5 passed (5).
A typical mistake: state set during render
The first version from the agent, which you will find in many tutorials, kept the column heights in state:
// components/MasonryGrid.tsx (the agent's version)
const [columnHeights, setColumnHeights] = useState<number[]>(Array(columns).fill(0));
const distributePins = () => {
// ... the same loop as above
setColumnHeights(heights);
return columnArrays;
};
const columnArrays = distributePins();The render calls distributePins, which sets state with a new array, so React renders the component again, and that sets state again. For us the page answered with a 500 and the console showed Too many re-renders. React limits the number of renders to prevent an infinite loop. Nobody even read the columnHeights state. npm run lint caught the error before the browser did: Cannot call setState during render (the react-hooks/set-state-in-render rule), while npx tsc --noEmit stayed silent. The linter itself suggests the cure: data computed from props is computed during render, with no state. That is why MasonryGrid has a single line, const columns = distributePins(pins, columnCount).
What Claude wrote: the column count without a hydration error
The server renders the HTML before the browser sees it, so it does not know the window width. The agent likes to write typeof window === "undefined" ? 2 : .... For us the server sent "2", the browser counted "4", and React reported Hydration failed because the server rendered text didn't match the client. Hydration is the moment when React takes over the HTML from the server and attaches events to it. Open lib/columns.ts:
// lib/columns.ts
export function useColumnCount(): number {
return useSyncExternalStore(
subscribe,
() => columnsForWidth(window.innerWidth),
() => 2, // the server does not know the window width: it renders 2 columns, the browser corrects after hydration
);
}useSyncExternalStore is a React hook for values that change outside React. subscribe listens to the window resize event, the second function turns the width into 2, 3 or 4 columns, and the third is the version for the server. According to the React documentation it runs only on the server and during hydration, so the first render in the browser matches the HTML from the server, and right after that React renders again with the real width. The price is a flash of two columns on a wide screen. React compares the results with Object.is, so dragging the window edge within the same range gives no new render.
What Claude wrote: the pin card
Open components/PinCard.tsx. The photo:
// components/PinCard.tsx
<figure className="group relative overflow-hidden rounded-2xl" style={{ backgroundColor: pin.dominantColor }}>
<Image
src={pin.src}
alt={pin.title}
width={pin.width}
height={pin.height}
sizes="(min-width: 1024px) 25vw, (min-width: 768px) 33vw, 50vw"
loading={eager ? "eager" : "lazy"}
className="h-auto w-full"
/>According to the next/image documentation, the browser calculates the ratio from width and height and reserves the space before the image downloads. Until then you see a rectangle in the dominant colour, so the page does not jump. The pins from the first two rows get eager. The agent often writes priority here, which the Next.js 16 documentation marks as deprecated in favour of preload, and in most cases it advises loading="eager" or fetchPriority="high". preload also does not fit where the largest element can be one of several different images, as in a mosaic. An overlay lies on top of the photo:
// components/PinCard.tsx
<div className="absolute inset-0 flex flex-col justify-between bg-black/40 p-3 opacity-0 transition-opacity group-focus-within:opacity-100 group-hover:opacity-100">CSS alone shows the overlay: group-hover on mouse hover and group-focus-within when the focus is on a button inside. The old code did it twice at once, with an isHovered state and a group-hover class; one mechanism is enough, and CSS does not render the component on every mouse move. The Save button in the top right corner has an aria-label with the title, for example "Save pin: Bay at Dawn", because thirty-six identical "Save" buttons sound the same in a screen reader. It also has a focus-visible outline, and the title and author sit at the bottom. Each column is a ul list, so Tab first goes down the first column: that is the price of a masonry computed in JavaScript.
Infinite scrolling: the sentinel
The first page has twelve pins, and the next ones should arrive on their own when the viewer gets close to the end. The second request:
/plan Add infinite scrolling. A Route Handler GET /api/pins?cursor=
returns 12 pins and nextCursor (null at the end). The PinFeed component
loads the next page when a sentinel element under the grid gets close
to the screen: IntersectionObserver, the element through useRef. No
double requests and no stale values in the closure. At the end of the
list a message instead of the sentinel. Finish with lint, tsc and build.The route in app/api/pins/route.ts reads cursor from the address and returns getPinPage(cursor). Here the cursor is the number of the first pin of the next page. Open components/PinFeed.tsx and find the effect that watches the sentinel and loads further pages:
// components/PinFeed.tsx
useEffect(() => {
const sentinel = sentinelRef.current;
if (!sentinel || cursor === null) return;
let cancelled = false;
const observer = new IntersectionObserver(
(entries) => {
if (!entries[0].isIntersecting) return;
observer.disconnect(); // one page per sentinel entry
fetch(`/api/pins?cursor=${cursor}`)
.then((res) => res.json() as Promise<PinPage>)
.then((page) => {
if (cancelled) return;
setPins((prev) => [...prev, ...page.pins]);
setCursor(page.nextCursor);
});
},
{ rootMargin: "0px 0px 600px 0px" },
);
observer.observe(sentinel);
return () => {
cancelled = true;
observer.disconnect();
};
}, [cursor]);This is an abridgement: the real file also checks res.ok and shows an error message in .catch. The sentinel is an empty div under the grid, and IntersectionObserver signals when it enters the field of view. According to MDN, rootMargin widens the observed area, here by 600 pixels downward, so loading starts before the end of the list. cursor is in the effect dependencies, so each page gets a new observer with the current cursor and nothing reads a stale value. disconnect() after the first hit gives one request per sentinel entry, and prev => ... appends the pins to the freshest list. When nextCursor is null there is no observer, and in place of the sentinel stands the text "That's all the treasure on this map."
Captain's review
- State in render. Search the project (Cmd+Shift+F) for
setColumn. State set in the body of a component is reported bynpm run lint; never switch that rule off with a comment. - Hydration. Search for
typeof window, then open the page in a wide window: the console should be empty. For us Chrome showed 4 columns at 1280 pixels, 3 at 800 and 2 at 700, without a reload. - Keyboard. Open the page and press Tab. For us the focus landed on "Save pin: Bay at Dawn", the overlay appeared and the button got an outline.
- One request per page. In the Network tab scroll to the end. For us 36 pins arrived in two requests (
cursor=12andcursor=24), with no repeats, even though in development mode React runs effects twice. A typical agent mistake issetPins([...pins, ...fresh])in an effect with an empty dependency array: the closure still sees the first page, and a loading flag in state does not stop the second call. Symptom: the same pins twice and a warning about duplicate keys.
Next step
When the review passes, ask for a commit "Masonry grid with infinite scrolling". Then a small step: "When fetching a page fails, show a Try again button". In the next lesson the Save button gets chests. The editor below holds the column split in miniature: add pins one at a time, change the number of columns and watch which one is the shortest.
Remember: a good quartermaster puts each crate on the lowest stack and counts the stacks from the cargo list, instead of rewriting the logbook in the middle of counting.
Code for this lesson: App.tsx
// Masonry in miniature: add pins one at a time and watch which column is the shortest
import { useState } from 'react';
interface Pin {
id: string;
title: string;
width: number;
height: number;
dominantColor: string;
}
const PINS: Pin[] = [
{ id: 'p1', title: 'Bay at Dawn', width: 600, height: 400, dominantColor: '#289888' },
{ id: 'p2', title: 'Sunset over the Harbour', width: 600, height: 900, dominantColor: '#f8a858' },
{ id: 'p3', title: 'Island Jungle', width: 600, height: 750, dominantColor: '#284858' },
{ id: 'p4', title: 'Sand Under the Palm', width: 600, height: 600, dominantColor: '#e8c868' },
{ id: 'p5', title: 'Ocean Depths', width: 600, height: 1050, dominantColor: '#487898' },
{ id: 'p6', title: 'Coral Reef', width: 600, height: 500, dominantColor: '#e86868' },
{ id: 'p7', title: 'Lagoon', width: 600, height: 800, dominantColor: '#a8c808' },
{ id: 'p8', title: 'Gold in the Chest', width: 600, height: 450, dominantColor: '#f88808' },
{ id: 'p9', title: 'Night Watch', width: 600, height: 1200, dominantColor: '#080858' },
{ id: 'p10', title: 'Old Map', width: 600, height: 700, dominantColor: '#986848' },
{ id: 'p11', title: 'Wooden Deck', width: 600, height: 950, dominantColor: '#785838' },
{ id: 'p12', title: 'Flag in the Harbour', width: 600, height: 550, dominantColor: '#d8a898' },
];
// The pure function from the lesson: columns and their heights computed during render, with no state
function distributePins(pins: readonly Pin[], columnCount: number) {
const columns: Pin[][] = Array.from({ length: columnCount }, () => []);
const heights: number[] = new Array(columnCount).fill(0);
for (const pin of pins) {
const shortest = heights.indexOf(Math.min(...heights));
columns[shortest].push(pin);
heights[shortest] += pin.height / pin.width; // height when the column width is 1
}
return { columns, heights };
}
export default function App() {
const [placed, setPlaced] = useState(3);
const [columnCount, setColumnCount] = useState(3);
const { columns, heights } = distributePins(PINS.slice(0, placed), columnCount);
const next = PINS[placed];
const shortest = heights.indexOf(Math.min(...heights));
const lastId = PINS[placed - 1]?.id;
return (
<div className="min-h-screen bg-amber-50 p-4 text-zinc-900">
<h1 className="text-xl font-bold">A Treasure Map in Columns</h1>
<div className="my-3 flex flex-wrap items-center gap-2">
<button
type="button"
onClick={() => setPlaced((n) => Math.min(n + 1, PINS.length))}
disabled={!next}
className="rounded-full bg-red-600 px-4 py-2 font-semibold text-white disabled:bg-zinc-400"
>
Add pin
</button>
<button type="button" onClick={() => setPlaced(0)} className="rounded-full bg-zinc-200 px-4 py-2">
Start over
</button>
<label className="flex items-center gap-2">
Columns:
<select value={columnCount} onChange={(e) => setColumnCount(Number(e.target.value))} className="rounded border border-zinc-300 px-2 py-1">
<option value={2}>2 (phone)</option>
<option value={3}>3 (from 768 px)</option>
<option value={4}>4 (from 1024 px)</option>
</select>
</label>
</div>
<p role="status" className="mb-3 text-sm">
{next
? 'The next pin "' + next.title + '" (ratio ' + (next.height / next.width).toFixed(2) + ') goes to column ' + (shortest + 1) + '.'
: 'All the pins are on the map now.'}
</p>
<div className="flex items-start gap-3">
{columns.map((column, c) => (
<div key={c} className="min-w-0 flex-1">
<p className={c === shortest ? 'mb-1 text-xs font-bold text-red-700' : 'mb-1 text-xs text-zinc-500'}>
Column {c + 1}: {heights[c].toFixed(2)}
{c === shortest && next ? ' (shortest)' : ''}
</p>
<ul className="flex flex-col gap-2">
{column.map((pin) => (
<li
key={pin.id}
style={{ aspectRatio: pin.width + ' / ' + pin.height, backgroundColor: pin.dominantColor }}
className={pin.id === lastId ? 'flex items-end rounded-xl p-2 ring-4 ring-red-600' : 'flex items-end rounded-xl p-2'}
>
<span className="rounded bg-black/50 px-1 text-xs text-white">{pin.title}</span>
</li>
))}
</ul>
</div>
))}
</div>
<p className="mt-4 text-sm text-zinc-600">
Change the number of columns: the split is computed again from the same list, because it is the result of a function, not state.
</p>
</div>
);
}Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. You give Claude the sketch sketches/masonry.png. What will the sketch not tell it, so it has to be in the text of the request?
2. How does a masonry layout differ from an ordinary grid with rows?
These are 2 of 8 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Horizontal ordering
Put in order the line from distributePins that finds the number of the shortest column:
- Vertical ordering
Put in order the lines of the loop that distributes the pins among the columns:
- Code editor
Create a masonry layout for pins
- Horizontal ordering
Put in order the line from MasonryGrid that computes the columns during render, with no state:
- Click in order
Click the elements to build the call from useColumnCount:
- Code editor
Build a pin card with hover effects
- Vertical ordering
Put in order what happens in PinFeed when the viewer gets close to the end of the list:
- Click in order
Click the elements to build the line that tells the observer to watch the sentinel:
- Horizontal ordering
Put in order the line that appends new pins to the freshest list, not to a stale value from the closure:
- Click in order
Click the elements to build the calculation of the lowest column height:
- Vertical ordering
Put in order the layers of PinCard from the bottom (background) to the top:
Tasks after this lesson
- QuestionQuiz: A sketch as input
- QuestionQuiz: The masonry layout
- QuestionQuiz: The width and height fields of a pin
- Put in orderSorting: The number of the shortest column
- Put in orderSorting: The distributePins loop
- Coding taskPractice: Masonry grid
- QuestionQuiz: A ratio instead of pixels
- QuestionQuiz: The pin card overlay
- Put in orderSorting: A split computed in render
- Click in orderBuild: The column count without a hydration error
- Coding taskPractice: Pin card
- QuestionQuiz: The infinite scroll sentinel
- Put in orderSorting: Loading a page of pins
- Click in orderBuild: observer.observe(sentinel)
- QuestionQuiz: State set during render
- Put in orderSorting: Appending pins to the freshest list
- QuestionQuiz: The dominant colour before download
- Click in orderBuild: Math.min for columns
- Put in orderSorting: The layers of a pin card