CodingNic

Build Movie Discovery

Connect the Genre Filters

Build Movie Discovery 9 min read

Connect the Genre Filters

Connect the Genre Filters

Turn the genre chips into toggles that update the same URL state. Keep all of the existing chip markup and change only the behavior behind it.

Step 1 — Build the toggle calculation

Inside FilterBar, create toggleGenre. If the selected id is already active, remove it; otherwise append it.

typescript
function toggleGenre(id: number) {
  const next = activeGenreIds.includes(id)
    ? activeGenreIds.filter((x) => x !== id)
    : [...activeGenreIds, id];

Step 2 — Push the new selection

Pass the resulting array to the helper from the previous lesson.

typescript
pushParams({ genres: next });

Step 3 — Connect the chip button

Use the handler on each mapped chip.

tsx
onClick={() => toggleGenre(g.id)}

The existing active class already receives activeGenreIds, so the visual state will update automatically after the URL changes and the server rerenders the page.

Step 4 — Add a clear control

When at least one genre is active, render the existing clear button and point it at an empty genre array.

tsx
{activeGenreIds.length > 0 && (
  <button type="button" className="clear-chip" onClick={() => pushParams({ genres: [] })}>
    clear
  </button>
)}

Checkpoint

Click a genre chip. The URL should gain that genre id, the chip should become active, and the movie results should change. Click it again or use clear to remove the selection.