Frontend Blocks typescript Intermediate

Compound Component Pattern

Implement a flexible Tabs component using React Context and compound component pattern.

typescript
import { createContext, useContext, useState } from "react";

const Ctx = createContext<{ active: string; set: (s: string) => void } | null>(null);

export function Tabs({ children, defaultTab }: any) {
  const [active, set] = useState(defaultTab);
  return <Ctx.Provider value={{ active, set }}>{children}</Ctx.Provider>;
}

Tabs.Tab = function Tab({ id, children }: any) {
  const { active, set } = useContext(Ctx)!;
  return (
    <button
      onClick={() => set(id)}
      className={active === id ? "border-b-2 border-green-500 font-semibold" : "text-slate-400"}
    >{children}</button>
  );
};

Tabs.Panel = function Panel({ id, children }: any) {
  return useContext(Ctx)!.active === id ? <div>{children}</div> : null;
};

Prerequisites

  • React >= 17

Pro Tips

  • → Expose the context hook for advanced consumer customisation.

Was this module useful?

Share your experience — it helps the team improve.

Leave Feedback

Commercial Licensing

Acquire a production access token or template license for enterprise deployment.

Module Info

Language
typescript
Level
Intermediate
Read time
5 min
Published
Sep 2026
License
Commercial License

Newsletter

New modules every week, directly to your inbox.