Vibe coding with Claude Code course ยท Module 4: Instagram clone

Crew Reactions: Likes and Comments Under a Photo

10 min read ยท
In this lesson8

The gallery has a preview window but it is dead: you cannot like a photo or write anything under it. In this lesson Claude Code will add likes and comments, and you will check that every reaction lands under the right photo and survives closing the window.

The problem: a reaction must land in the right place

A like should change one photo, not all of them. It should be visible in two places at once: in the preview window and on the thumbnail in the grid, where on hover we will show the number of likes and comments, like on Instagram. And it should stay after the window is closed, although from lesson 3_2 you know that a closed window disappears from the screen entirely, together with its state.

This tells you where to keep the data. In lesson 2_3 the state of the posts went up, to the common parent of the form and the list. Here the common parent of the grid and the window is Gallery, so it holds the photos with their likes and comments, and the window gets data and functions to change them.

Request for Claude Code

The change touches three files and leaves choices, so you start with a plan. The request says outright where the state should live and what not to use in the starting data:

Request for Claude Code:

/plan Add likes and comments to Treasure Gallery. In @lib/photos.ts
every photo gets likes, likedByMe and a comments array (id, author,
text, createdAt as an ISO string). Hardcode the starting values, no
Math.random() and no new Date(). The state of the photos lives in
@components/Gallery.tsx, and @components/PhotoModal.tsx gets the
functions onToggleLike and onAddComment. In the window: a Like button,
the like count, the caption, a list of comments and a form. On a
thumbnail on hover the number of likes and comments. End every step
with npm run build and npm run lint.

In the plan look for the three files from the request and nothing more: no new package, no useState with likes inside PhotoModal. Accept it with Yes, manually approve edits and read every edit.

What Claude wrote: the shape of the data

Open lib/photos.ts. The photo type grew by three fields, and next to it appeared the comment type:

export interface Comment {
  id: string;
  author: string;
  text: string;
  createdAt: string;
}

export interface Photo {
  id: string;
  src: string;
  alt: string;
  author: string;
  caption: string;
  likes: number;
  likedByMe: boolean;
  comments: Comment[];
}

likes is the number of likes, and likedByMe says whether yours is among them. Comments have no separate state, they are part of the photo, so a new comment changes one photo in the list. createdAt is a text in ISO format, for the same reason as in lesson 2_3. This is a fragment of the starting data of the first photo:

likes: 42,
likedByMe: false,
comments: [
  {
    id: "k1",
    author: "Polly",
    text: "Where is this?",
    createdAt: "2026-11-12T12:00:00.000Z",
  },
],

The identifier and the date are hardcoded. Why that matters, the captain's review will explain.

Open components/Gallery.tsx. At the top of the component stand two states and one computed value:

const [items, setItems] = useState(photos);
const [selectedId, setSelectedId] = useState<string | null>(null);
const selected = items.find((photo) => photo.id === selectedId) ?? null;

items are the photos with reactions, and the starting value comes from the photos prop. Instead of the whole selected photo the state holds only its id. Claude computes the photo itself on every render from the current array, like the character counter in lesson 2_3, so the window always shows the latest data. ?? null gives null when nothing is selected.

A like is toggled by the toggleLike function:

const toggleLike = (id: string) => {
  setItems((prev) =>
    prev.map((photo) =>
      photo.id === id
        ? {
            ...photo,
            likedByMe: !photo.likedByMe,
            likes: photo.likedByMe ? photo.likes - 1 : photo.likes + 1,
          }
        : photo,
    ),
  );
};

The setter gets a function instead of a value: prev is always the current array, even when several changes arrive right after one another. map builds a new array in which the photo with the matching id is a new copy with a spread (...photo), and the rest stay unchanged. If it was liked, the count goes down by one; if not, it goes up.

A comment is added by addComment:

const addComment = (id: string, text: string) => {
  const comment: Comment = {
    id: String(Date.now()),
    author: "You",
    text,
    createdAt: new Date().toISOString(),
  };
  setItems((prev) =>
    prev.map((photo) =>
      photo.id === id
        ? { ...photo, comments: [...photo.comments, comment] }
        : photo,
    ),
  );
};

[...photo.comments, comment] is a new array with the new entry at the end, and the old one stays untouched. Date.now() and new Date() are fine here, because this function runs after a click, not while the component is being drawn.

What Claude wrote: the window like a post

Open components/PhotoModal.tsx. Under the photo stand the actions, the caption and the comments, in the same order as in an Instagram post. The like button looks like this:

<button
  type="button"
  onClick={() => onToggleLike(photo.id)}
  aria-pressed={photo.likedByMe}
  className={photo.likedByMe ? "font-semibold text-red-600" : "font-semibold"}
>
  {photo.likedByMe ? "Liked" : "Like"}
</button>

The window does not change data itself, it only calls the parent's function with the photo's id. aria-pressed tells a screen reader that this is a toggle and whether it is on. Under the button stand the like count, the caption and the comments:

{photo.comments.length === 0 && (
  <p className="text-gray-500">Nobody has commented yet.</p>
)}
<ul className="space-y-1">
  {photo.comments.map((comment) => (
    <li key={comment.id}>
      <span className="font-semibold">{comment.author}</span> {comment.text}
    </li>
  ))}
</ul>

The encouragement text appears only with an empty list, and every comment has a key from its own id, not from the index (lesson 2_8). The content stands in curly braces as plain text; in a moment you will see why that matters.

The form under the list is the controlled form from lesson 2_3. The field has value={draft}, and onChange saves every change through setDraft. The draft state lives in the window, because nobody else needs it. Submitting is handled by a function:

const handleSubmit = (event: React.SubmitEvent<HTMLFormElement>) => {
  event.preventDefault();
  const text = draft.trim();
  if (!text) return;
  onAddComment(photo.id, text);
  setDraft("");
};

preventDefault() blocks the page reload, trim() cuts off spaces, empty text ends the function, and after submitting the field is cleared. The Post button has disabled={!draft.trim()}, so an empty comment does not even leave the form.

The counter on a thumbnail

The grid in Gallery.tsx now draws tiles from items.map(...), not from photos.map(...), because only items knows the current likes. On a thumbnail Claude added an overlay. The tile button got the group class, and inside, above the image, stands:

<span className="absolute inset-0 flex items-center justify-center gap-4 bg-black/50 font-semibold text-white opacity-0 transition-opacity group-hover:opacity-100">
  <span>Likes: {photo.likes}</span>
  <span>Comments: {photo.comments.length}</span>
</span>

The overlay starts invisible (opacity-0). When the cursor moves onto the parent with the group class, group-hover:opacity-100 shows it, and absolute inset-0 stretches it over the whole tile, which has relative. In Tailwind 4 the hover: variants work only on devices with a cursor, so on a phone you will not see the overlay. That is why the like count also stands in the window.

Captain's review

Run the page and check:

  1. The window and the grid say the same. Like a photo in the window: the label changes to Liked, and the count goes up by one in the window and in the overlay on the thumbnail. A second click goes back to the starting number. A typical agent mistake is leaving the state from lesson 3_2, that is, the whole photo instead of its id:
const [selected, setSelected] = useState<Photo | null>(null);

TypeScript, build and lint pass, and after a click the grid shows 43, the window still 42 and the label Like. The window holds an old copy of the photo from before the like. In the diff look for a state with a whole object where an id is enough.

  1. A like survives closing the window. Like, close, open again. If Claude gave the window its own toggle, for example const [liked, setLiked] = useState(false) with setLiked((prev) => !prev), the toggle would work but disappear together with the window. prev => !prev is a good way for a toggle that lives in one component. Data visible in two places, however, belongs to the parent.

  2. Crew content is text. Under the second photo add the comment <img src=x onerror=alert(1)>. It should appear only under that photo and entirely as plain text. No dialog may pop up. React turns characters in curly braces into text, so nobody smuggles in a script. dangerouslySetInnerHTML switches off this protection and inserts the text as HTML. A rule for the whole course: content from users (comments, captions, posts) you never show through dangerouslySetInnerHTML, even when Claude suggests it "for formatting". Search the project for that name: zero hits.

  3. Starting data without randomness and a clock. A common agent shortcut is starting data written into the component with id: Math.random() or createdAt: new Date(). The first case is caught by npm run lint:

error  Error: Cannot call impure function during render

`Math.random` is an impure function. Calling an impure function can produce unstable results that update unpredictably when the component happens to re-render.

This is the react-hooks/purity rule. An impure function is one that returns something different on every call, while a component should draw the same thing for the same data. The linter lets new Date() through, which is a pity: we checked that the time from new Date() in the starting state of a component looks fine in npm run dev, but after npm run build and npm run start everybody sees the build time, because the page was created then. The cure is in the data above: hardcoded starting values, new ones only in an event handler.

Next step

When the review passes, ask for a commit. The screen changes for us right after the click, without waiting for any server. When likes someday go to a database, this approach is called Optimistic UI: you show the change immediately, the save flies off in the background, and when it fails, the state goes back to the previous one. For now a small extension:

In @components/PhotoModal.tsx, when a photo has more than three
comments, show the last three and a button "Show all (count)". Change
nothing outside this file.

Whether the list is expanded is view state, needed only by the window, so it can live in it and disappear together with it. If Claude moves it to Gallery, ask why.

In the editor below waits a gallery with likes and comments: like a photo, close the window, open it again and add a comment with HTML to see that it stays plain text.

Remember: you write the crew's reactions in one logbook on the bridge, and the window only shows it, because a lifeboat that sails away after closing is no place for a logbook.

Code for this lesson: App.jsx
// Likes and comments: the state lives in the gallery, the window only shows it
import { useEffect, useState } from 'react';

const startPhotos = [
  {
    id: 'zachod-na-plazy',
    src: 'https://images.unsplash.com/photo-1507525428034-b723cf961d3e?w=600',
    alt: 'Waves on a sandy beach at sunset',
    author: 'Morgan',
    caption: 'We buried the chest here',
    likes: 42,
    likedByMe: false,
    comments: [
      { id: 'k1', author: 'Polly', text: 'Where is this?', createdAt: '2026-11-12T12:00:00.000Z' },
    ],
  },
  {
    id: 'fale-z-gory',
    src: 'https://images.unsplash.com/photo-1505118380757-91f5f5632de0?w=600',
    alt: 'Turquoise waves at a white beach seen from above',
    author: 'Polly',
    caption: 'The bay from the lookout',
    likes: 17,
    likedByMe: false,
    comments: [],
  },
  {
    id: 'zaglowka-noca',
    src: 'https://images.unsplash.com/photo-1534447677768-be436bb09401?w=600',
    alt: 'A small sailboat on a calm sea under a starry sky',
    author: 'Kapitan Redbeard',
    caption: 'Night watch',
    likes: 8,
    likedByMe: false,
    comments: [],
  },
];

function PhotoModal({ photo, onClose, onToggleLike, onAddComment }) {
  const [draft, setDraft] = useState('');

  useEffect(() => {
    const handleKeyDown = (event) => {
      if (event.key === 'Escape') onClose();
    };
    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [onClose]);

  useEffect(() => {
    const previous = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      document.body.style.overflow = previous;
    };
  }, []);

  const handleSubmit = (event) => {
    event.preventDefault();
    const text = draft.trim();
    if (!text) return;
    onAddComment(photo.id, text);
    setDraft('');
  };

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/80 p-4"
      onClick={onClose}
    >
      <div
        role="dialog"
        aria-modal="true"
        aria-labelledby="photo-modal-title"
        className="max-h-[90vh] w-full max-w-md overflow-y-auto rounded-lg bg-white text-gray-900"
        onClick={(event) => event.stopPropagation()}
      >
        <div className="flex items-center justify-between p-3">
          <h2 id="photo-modal-title" className="font-semibold">{photo.author}</h2>
          <button
            type="button"
            onClick={onClose}
            aria-label="Close preview"
            autoFocus
            className="rounded px-2 text-2xl leading-none"
          >
            ร—
          </button>
        </div>
        <div className="relative h-48 bg-black">
          <img src={photo.src} alt={photo.alt} className="absolute inset-0 h-full w-full object-contain" />
        </div>
        <div className="space-y-2 p-3 text-sm">
          <button
            type="button"
            onClick={() => onToggleLike(photo.id)}
            aria-pressed={photo.likedByMe}
            className={photo.likedByMe ? 'font-semibold text-red-600' : 'font-semibold'}
          >
            {photo.likedByMe ? 'Liked' : 'Like'}
          </button>
          <p className="font-semibold">Likes: {photo.likes}</p>
          <p>
            <span className="font-semibold">{photo.author}</span> {photo.caption}
          </p>
          {photo.comments.length === 0 && (
            <p className="text-gray-500">Nobody has commented yet.</p>
          )}
          <ul className="space-y-1">
            {photo.comments.map((comment) => (
              <li key={comment.id}>
                {/* Content as plain text: React will not run HTML from a comment */}
                <span className="font-semibold">{comment.author}</span> {comment.text}
              </li>
            ))}
          </ul>
          <form onSubmit={handleSubmit} className="flex gap-2 border-t border-gray-200 pt-2">
            <input
              value={draft}
              onChange={(event) => setDraft(event.target.value)}
              placeholder="Add a comment..."
              aria-label="Comment text"
              maxLength={300}
              className="flex-1 outline-hidden"
            />
            <button
              type="submit"
              disabled={!draft.trim()}
              className="font-semibold text-blue-600 disabled:text-blue-300"
            >
              Post
            </button>
          </form>
        </div>
      </div>
    </div>
  );
}

export default function App() {
  const [items, setItems] = useState(startPhotos);
  const [selectedId, setSelectedId] = useState(null);
  const selected = items.find((photo) => photo.id === selectedId) ?? null;

  const toggleLike = (id) => {
    setItems((prev) =>
      prev.map((photo) =>
        photo.id === id
          ? {
              ...photo,
              likedByMe: !photo.likedByMe,
              likes: photo.likedByMe ? photo.likes - 1 : photo.likes + 1,
            }
          : photo,
      ),
    );
  };

  // Date.now() and new Date() only here: this function runs after a click
  const addComment = (id, text) => {
    const comment = {
      id: String(Date.now()),
      author: 'You',
      text,
      createdAt: new Date().toISOString(),
    };
    setItems((prev) =>
      prev.map((photo) =>
        photo.id === id
          ? { ...photo, comments: [...photo.comments, comment] }
          : photo,
      ),
    );
  };

  return (
    <div className="min-h-screen bg-slate-100 p-4 text-slate-900">
      <h1 className="mb-4 text-2xl font-bold">Treasure Gallery</h1>
      <ul className="grid grid-cols-1 gap-1 sm:grid-cols-3">
        {items.map((photo) => (
          <li key={photo.id}>
            <button
              type="button"
              onClick={() => setSelectedId(photo.id)}
              className="group relative block aspect-square w-full cursor-pointer"
            >
              <img src={photo.src} alt={photo.alt} className="absolute inset-0 h-full w-full object-cover" />
              <span className="absolute inset-0 flex items-center justify-center gap-4 bg-black/50 text-sm font-semibold text-white opacity-0 transition-opacity group-hover:opacity-100">
                <span>Likes: {photo.likes}</span>
                <span>Comments: {photo.comments.length}</span>
              </span>
            </button>
          </li>
        ))}
      </ul>

      {selected && (
        <PhotoModal
          photo={selected}
          onClose={() => setSelectedId(null)}
          onToggleLike={toggleLike}
          onAddComment={addComment}
        />
      )}
    </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. 1. How do you increase the like count of only one photo in the items array?

  2. 2. Which two properties make a controlled input in React?

These are 2 of 12 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Click in order

    Click the pieces in order so that the button in the window calls the parent's function with the photo id:

  • Horizontal ordering

    Arrange the pieces of the expression that creates a new comments array with a new entry at the end:

  • Code editor

    Interactive like button

  • Vertical ordering

    Arrange the steps of the handleSubmit function that submits a comment:

  • Code editor

    Comment system

  • Click in order

    Click the pieces in order to compute the selected photo from the current items array:

  • Vertical ordering

    Arrange the lines of the function that toggles the like of one photo (top to bottom):

  • Vertical ordering

    Arrange the sections of the preview window in the order of an Instagram post (top to bottom):

  • Code editor

    Full Instagram post

  • Horizontal ordering

    Arrange the pieces of the expression that draws a tile for each photo in the grid:

  • Click in order

    Click the pieces in order so that the like count goes down when a like is undone and up for a new one:

  • Vertical ordering

    Arrange the steps of how the overlay with the like count on a thumbnail works:

  • Horizontal ordering

    Arrange the conditions of the grid's sizes attribute from the left (with min-width the browser takes the first matching condition):

  • Vertical ordering

    Arrange the elements of a gallery tile as they stand in the code (top to bottom):

  • Horizontal ordering

    Arrange the responsive gallery classes in a single line (grid + mobile โ†’ tablet โ†’ desktop):

  • Vertical ordering

    Arrange what happens before the Post button submits a comment:

  1. QuestionQuiz: Liking One Photo
  2. QuestionQuiz: Controlled Field
  3. Click in orderClicking: The Like Button
  4. Put in orderSorting: Adding a Comment to the Array
  5. Coding taskPractice: Like button
  6. QuestionQuiz: A Toggle with the Previous Value
  7. Put in orderSorting: Submitting a Comment
  8. Coding taskPractice: Comment system
  9. QuestionQuiz: Optimistic UI
  10. QuestionQuiz: Text for an Empty List
  11. Click in orderClicking: The Selected Photo from the Array
  12. Put in orderSorting: Toggling a Like in map
  13. Put in orderSorting: Window Layout Like a Post
  14. Coding taskPractice: Complete Instagram post
  15. QuestionQuiz: preventDefault in the Form
  16. Put in orderSorting: Tiles from the Photo List
  17. QuestionQuiz: Lazy Loading
  18. QuestionQuiz: key in a List
  19. QuestionQuiz: CLS and Image
  20. Click in orderClicking: New Like Count
  21. Put in orderSorting: Hover Overlay
  22. Put in orderSorting: sizes for the Grid
  23. QuestionQuiz: Undoing a Like
  24. Put in orderSorting: A Gallery Tile in Code
  25. QuestionQuiz: Two States in Gallery
  26. Put in orderSorting: Responsive grid tokens from mobile
  27. QuestionQuiz: Blocking Scrolling Under the Window
  28. Put in orderSorting: The Post Button

Useful articles