Skip to lesson content

PROJECT 1 · LESSON 3 OF 18

Refactor cards and add interaction

Extract repeated markup and isolate a small interactive component.

  • props
  • composition
  • Server Components
  • use client

Your workspace: edushop

Continue from lesson 2: Add pages and shared navigation. Keep existing files; create or replace the complete files listed below.

Extract the ZIP, open its project folder, and run npm install. Database lessons also need the .env.local setup described below. Checkpoints never contain credentials or node_modules.

1. Understand the problem and the concepts

Why we need this feature

Repeated markup is manageable until a design change must be made everywhere. Interaction adds a second question: where does the code execute? This lesson separates reusable presentation from the small part that needs browser state.

First write two cards directly on the home page. Change the appearance of both. Now replace that repetition with FeatureCard: the component owns the markup and props supply the differences.

Pages and layouts are Server Components by default. State and click handlers belong in Client Components. A client boundary is not a command to turn the whole page into browser code. Client Components can also be prerendered on the server.

Refactor after identifying what varies

The two feature cards share an article, heading and paragraph. Only the title and body differ. FeatureCard keeps the stable markup in one place and accepts those differences as props. A prop is an input from the parent; the component should not change the parent’s value.

children is another prop, populated by the content between <FeatureCard> and </FeatureCard>. React.ReactNode accepts renderable content, including text and elements. A string-only body prop would be narrower. We use children because the card’s body can naturally contain more than one kind of content.

Understand the server/client boundary before adding a hook

The home page and FeatureCard use no state, effects or browser event handlers, so they can remain Server Components. FAQ imports useState and attaches an onClick handler; its module begins with use client. That directive establishes an entry into the client module graph, including modules it imports at runtime.

Client Component does not mean “never rendered on the server.” On an initial page load, Next.js can render a preview of its HTML on the server. The browser then hydrates it, connecting the client logic to that markup. Browser-only objects such as localStorage still cannot be read unconditionally during rendering.

A Server Component may render FAQ and pass serializable data into it. It should not pass a normal server-defined event handler across that boundary. The click handler belongs in FAQ because it responds to browser interaction.

Read the FAQ state transition

useState(false) gives the component a current open value and a setter. During the first render, open is false and the conditional answer is absent. A click calls setOpen with the opposite boolean. React renders again using the new value, so the answer becomes visible.

aria-expanded communicates the same open state to assistive technology. aria-controls identifies the controlled answer element. The semantic button already supports keyboard activation; a clickable div would require extra work to provide that behavior.

2. Follow the execution flow

Read this sequence before the source. Identify the input, the component or function that handles it, and the result the learner sees.

  1. The server composes the home page, reusable cards and FAQ preview.

  2. The browser loads and hydrates the FAQ client code.

  3. A click requests a state update from false to true.

  4. React renders the answer and updates aria-expanded to match.

Follow a single click

  1. Before clicking, open is false, aria-expanded is false and no answer paragraph is rendered.
  2. The event handler evaluates !open as true and passes that value to setOpen.
  3. The next render sees true and includes the paragraph with id delivery-answer.
  4. Clicking again schedules false and removes the paragraph. No database or Server Action is involved.

3. Build it, one file at a time

  1. Replace the home page and add the two components below.
  2. Click the question to reveal its answer.
  3. Keep the home page as a Server Component; only the FAQ needs use client.

The paths below are relative to your practice project. Each block is the complete file at this checkpoint. Read its responsibility first, type or copy the code, then use the walkthrough to explain the important statements.

components/feature-card.tsx

This owns the markup shared by all feature cards.

components/feature-card.tsx
export default function FeatureCard({
  title,
  children,
}: {
  title: string;
  children: React.ReactNode;
}) {
  return (
    <article>
      <h2>{title}</h2>
      <p>{children}</p>
    </article>
  );
}

Read the code

  1. The props type requires a title string and renderable children. Destructuring gives those values local names.
  2. The title goes inside h2 and children inside the paragraph. React inserts the supplied values into the same reusable structure.
  3. There is no state or click handler here, so no client directive is needed.

components/faq.tsx

This is a small interactive island within the server-rendered home page.

components/faq.tsx
"use client";
import { useState } from "react";
export default function FAQ() {
  const [open, setOpen] = useState(false);
  return (
    <section>
      <button
        type="button"
        aria-expanded={open}
        aria-controls="delivery-answer"
        onClick={() => setOpen(!open)}
      >
        When will my order arrive?
      </button>
      {open && (
        <p id="delivery-answer">Our demo store does not ship real orders.</p>
      )}
    </section>
  );
}

Read the code

  1. use client allows the module to use state and attach browser handlers. useState(false) initializes this FAQ instance as closed.
  2. onClick calls the setter; it does not directly edit the DOM. React rerenders and the open && expression decides whether to include the answer.
  3. aria-expanded mirrors the state and aria-controls names the answer. Keep IDs unique if you extend the page with several FAQ instances.

app/page.tsx

This composes the refactored home page from reusable cards and one interactive FAQ.

app/page.tsx
import FeatureCard from "@/components/feature-card";
import FAQ from "@/components/faq";
export default function Home() {
  return (
    <>
      <h1>Welcome to EduShop</h1>
      <div className="grid">
        <FeatureCard title="Learn">Build with useful supplies.</FeatureCard>
        <FeatureCard title="Practice">
          Small projects make ideas concrete.
        </FeatureCard>
      </div>
      <FAQ />
    </>
  );
}

Read the code

  1. Imports make the component implementations available; rendering them creates separate instances.
  2. title supplies a named prop, while the text between FeatureCard tags becomes children.
  3. The page remains a Server Component. FAQ declares its own client boundary, so the page does not need to adopt one just to render it.

4. Run it and check your result

  • Both cards share one component.
  • The FAQ opens with keyboard or mouse and closes on a second click.

5. Predict, change and observe

Render two FAQ components on the page temporarily. Click the first one.

Compare your prediction with the expected result

What you should observe

Only the clicked instance changes its open state.

Why it happens

Each mounted instance has its own state. Reusing a component shares its implementation, not automatically its live state. Use distinct controlled-element IDs if keeping multiple FAQ instances.

6. Troubleshoot with evidence

A common mistake

Putting use client in the root layout pulls unnecessary code into the client module graph. Keep the boundary around the interactive component.

Next.js reports that useState needs a Client Component.

Likely cause: The interactive module lacks a client boundary.

Check and correct: Put use client at the top of the FAQ file before imports.

You put use client in every file to silence the error.

Likely cause: The boundary was moved higher than necessary.

Check and correct: Keep it on the interactive entry module. Let pages and static cards remain server-rendered components.

7. Practice and explain it back

Your independent task

Add a third card by supplying new props; do not copy the card markup.

Attempt these questions before opening the explanations. Use the source above to justify your answer.

Why is FeatureCard a component instead of copied HTML?

It gives the repeated structure one owner. Changing that owner updates all instances while props retain their different content.

Does use client protect secrets?

No. It marks code intended for the client module graph. Secrets and database access belong in server-only modules, never in a client component.