Skip to main content

Lesson 8 of 8

Practice & Quiz - Component Patterns

Test your mastery of Compound Components, Render Props, HOCs, and headless patterns with a practical Accordion exercise and 5 quiz questions.

10 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Practical Exercise - Compound Component Accordion

Practical Exercise - Compound Component Accordion
import { createContext, useContext, useState, useId } from 'react';

// ─── Context - shared state between Accordion and its children ─
interface AccordionCtx {
  openId: string | null;
  toggle: (id: string) => void;
}
const Ctx = createContext<AccordionCtx | null>(null);
const useAccordion = () => {
  const ctx = useContext(Ctx);
  if (!ctx) throw new Error('Use AccordionItem inside Accordion');
  return ctx;
};

// ─── Root ─────────────────────────────────────────────────────
function Accordion({ children, defaultOpen }: { children: React.ReactNode; defaultOpen?: string }) {
  const [openId, setOpenId] = useState<string | null>(defaultOpen ?? null);
  const toggle = (id: string) => setOpenId(prev => (prev === id ? null : id));
  return <Ctx.Provider value={{ openId, toggle }}><div className="accordion">{children}</div></Ctx.Provider>;
}

// ─── Item - knows its own id ──────────────────────────────────
function AccordionItem({ id, children }: { id: string; children: React.ReactNode }) {
  const uid = useId();
  const panelId = `panel-${uid}-${id}`;
  const triggerId = `trigger-${uid}-${id}`;
  const { openId, toggle } = useAccordion();
  const isOpen = openId === id;

  // Find header and panel children by display name
  const header = (children as React.ReactElement[]).find(
    (c: React.ReactElement) => (c.type as { displayName?: string }).displayName === 'AccordionHeader'
  );
  const panel = (children as React.ReactElement[]).find(
    (c: React.ReactElement) => (c.type as { displayName?: string }).displayName === 'AccordionPanel'
  );

  return (
    <div className="accordion-item">
      <h3>
        <button
          id={triggerId}
          aria-expanded={isOpen}
          aria-controls={panelId}
          onClick={() => toggle(id)}
          style={{ width: '100%', textAlign: 'left' }}
        >
          {header}
          <span aria-hidden>{isOpen ? '▲' : '▼'}</span>
        </button>
      </h3>
      <div
        id={panelId}
        role="region"
        aria-labelledby={triggerId}
        hidden={!isOpen}
      >
        {panel}
      </div>
    </div>
  );
}

// ─── Sub-components ───────────────────────────────────────────
const AccordionHeader = ({ children }: { children: React.ReactNode }) => <>{children}</>;
AccordionHeader.displayName = 'AccordionHeader';
const AccordionPanel = ({ children }: { children: React.ReactNode }) => <>{children}</>;
AccordionPanel.displayName = 'AccordionPanel';

Accordion.Item   = AccordionItem;
Accordion.Header = AccordionHeader;
Accordion.Panel  = AccordionPanel;

// ─── Usage - clean, expressive API ───────────────────────────
export default function FAQ() {
  return (
    <Accordion defaultOpen="q1">
      <Accordion.Item id="q1">
        <Accordion.Header>What is React?</Accordion.Header>
        <Accordion.Panel>A UI library for building component trees.</Accordion.Panel>
      </Accordion.Item>
      <Accordion.Item id="q2">
        <Accordion.Header>What is Compound Component?</Accordion.Header>
        <Accordion.Panel>Components that share state via Context with a clean API.</Accordion.Panel>
      </Accordion.Item>
    </Accordion>
  );
}

Module Quiz

Module Quiz
Question 1 of 5

What problem does the Compound Component pattern solve?

Tip

Tip

Practice Practice Quiz Component Patterns in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Modern React: Use Hooks instead of class lifecycle methods

Practice Task

Note

Practice Task - (1) Write a working example of Practice Quiz Component Patterns from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with Practice Quiz Component Patterns is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/8 done