Adds Chakra UI CLI, self-hosted fonts, and prettier config
Moves prettier config into web/, adds @chakra-ui/cli for typegen and the fontsource font packages needed for self-hosted Jost and Marcellus, and brings in the chakra-ui-* skill docs.
This commit is contained in:
@@ -0,0 +1,374 @@
|
|||||||
|
---
|
||||||
|
name: chakra-ui-builder
|
||||||
|
description: >
|
||||||
|
Build responsive, accessible UI components and layouts using Chakra UI v3,
|
||||||
|
install or configure Chakra UI in new and existing projects, and design
|
||||||
|
scalable themes using tokens, semantic tokens, recipes, and slot recipes. Use
|
||||||
|
this skill whenever a user asks to build, create, or generate any UI
|
||||||
|
component, page, form, dashboard, navbar, card, landing section, pricing
|
||||||
|
table, or layout using Chakra UI; wants to add Chakra UI to a project, set up
|
||||||
|
ChakraProvider, run CLI snippets, configure color mode, or fix provider
|
||||||
|
wrapping; or asks about theming — defining brand colors, design tokens,
|
||||||
|
semantic tokens, dark mode values, component recipes, slot recipes, typegen,
|
||||||
|
or ejecting the default theme. Trigger on any Chakra UI building, setup, or
|
||||||
|
theming or charts request, however casually phrased — "add my brand colors",
|
||||||
|
"make a reusable card style", "build a bar chart", "show me a line chart",
|
||||||
|
"make me a login form", "build a sidebar", "add Chakra to my app".
|
||||||
|
---
|
||||||
|
|
||||||
|
# Chakra UI Builder
|
||||||
|
|
||||||
|
You are building UI with Chakra UI v3 and helping developers set up Chakra UI in
|
||||||
|
their projects. Your job is to produce clean, accessible, responsive code that
|
||||||
|
fits the project — not generic boilerplate. Read the project context first, then
|
||||||
|
build or set up.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 1 — Read the project context
|
||||||
|
|
||||||
|
Check `package.json` if available. Look for:
|
||||||
|
|
||||||
|
- Chakra UI version (use v3 patterns by default; only use v2 if explicitly on
|
||||||
|
v2)
|
||||||
|
- Framework: Next.js App Router, Pages Router, Vite, plain React
|
||||||
|
- TypeScript or JavaScript
|
||||||
|
- Package manager (from lockfile: `pnpm-lock.yaml`, `yarn.lock`, `bun.lock`,
|
||||||
|
`package-lock.json`)
|
||||||
|
|
||||||
|
Also glance at existing components if the user references them, so your code
|
||||||
|
matches the conventions already in use (naming, file structure, import style).
|
||||||
|
|
||||||
|
If the requirements are vague or the component is complex enough that choices
|
||||||
|
matter (layout direction, data shape, color palette, number of variants), ask
|
||||||
|
before building rather than generating something that needs to be thrown away.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Project setup
|
||||||
|
|
||||||
|
If Chakra UI isn't installed yet, complete setup before building.
|
||||||
|
|
||||||
|
### Install
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# npm
|
||||||
|
npm install @chakra-ui/react @emotion/react
|
||||||
|
|
||||||
|
# pnpm
|
||||||
|
pnpm add @chakra-ui/react @emotion/react
|
||||||
|
|
||||||
|
# yarn
|
||||||
|
yarn add @chakra-ui/react @emotion/react
|
||||||
|
|
||||||
|
# bun
|
||||||
|
bun add @chakra-ui/react @emotion/react
|
||||||
|
```
|
||||||
|
|
||||||
|
### Generate snippets with the CLI
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx @chakra-ui/cli snippet add
|
||||||
|
```
|
||||||
|
|
||||||
|
With no arguments this adds the recommended set — `provider`, `toaster`, and
|
||||||
|
`tooltip` — and automatically installs required dependencies (including
|
||||||
|
`next-themes`). Use `--all` to add every snippet, or `snippet list` to browse
|
||||||
|
first.
|
||||||
|
|
||||||
|
The CLI detects your framework and writes files to the right place:
|
||||||
|
|
||||||
|
| Framework | Output path |
|
||||||
|
| --------------------- | -------------------- |
|
||||||
|
| Next.js (with `src/`) | `src/components/ui/` |
|
||||||
|
| Next.js (no `src/`) | `components/ui/` |
|
||||||
|
| Vite / plain React | `src/components/ui/` |
|
||||||
|
| Remix | `app/components/ui/` |
|
||||||
|
|
||||||
|
### Wire up the Provider
|
||||||
|
|
||||||
|
**Next.js App Router** (`app/layout.tsx`):
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { Provider } from "@/components/ui/provider"
|
||||||
|
|
||||||
|
export default function RootLayout({
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
children: React.ReactNode
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<html lang="en" suppressHydrationWarning>
|
||||||
|
<body>
|
||||||
|
<Provider>{children}</Provider>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`suppressHydrationWarning` prevents a mismatch caused by `next-themes` injecting
|
||||||
|
the color-mode class. Do **not** add `"use client"` to `layout.tsx` — the
|
||||||
|
generated provider file already has it.
|
||||||
|
|
||||||
|
**Next.js Pages Router** (`pages/_app.tsx`):
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { Provider } from "@/components/ui/provider"
|
||||||
|
|
||||||
|
export default function App({ Component, pageProps }) {
|
||||||
|
return (
|
||||||
|
<Provider>
|
||||||
|
<Component {...pageProps} />
|
||||||
|
</Provider>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Vite** (`src/main.tsx`):
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { Provider } from "./components/ui/provider"
|
||||||
|
|
||||||
|
createRoot(document.getElementById("root")!).render(
|
||||||
|
<StrictMode>
|
||||||
|
<Provider>
|
||||||
|
<App />
|
||||||
|
</Provider>
|
||||||
|
</StrictMode>,
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Manual Provider (if CLI is unavailable)
|
||||||
|
|
||||||
|
If the CLI fails, create `components/ui/provider.tsx` manually and install
|
||||||
|
`next-themes` separately:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
"use client"
|
||||||
|
import { ChakraProvider, defaultSystem } from "@chakra-ui/react"
|
||||||
|
import { ThemeProvider } from "next-themes"
|
||||||
|
|
||||||
|
export function Provider({ children }: { children: React.ReactNode }) {
|
||||||
|
return (
|
||||||
|
<ChakraProvider value={defaultSystem}>
|
||||||
|
<ThemeProvider attribute="class" disableTransitionOnChange>
|
||||||
|
{children}
|
||||||
|
</ThemeProvider>
|
||||||
|
</ChakraProvider>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Common setup issues
|
||||||
|
|
||||||
|
- **Unstyled components** — app is not wrapped in `<Provider>`. Check the import
|
||||||
|
path and that `Provider` wraps the component tree.
|
||||||
|
- **Hydration mismatch** — add `suppressHydrationWarning` to `<html>` in App
|
||||||
|
Router.
|
||||||
|
- **`next-themes` not found** — install it: `npm install next-themes` (only
|
||||||
|
needed for the manual fallback; the CLI handles it automatically).
|
||||||
|
- **`extendTheme` not exported** — this is a v2 pattern. Use `createSystem` in
|
||||||
|
v3.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 2 — Choose the right layout primitives
|
||||||
|
|
||||||
|
Reach for the right Chakra primitive rather than wrapping everything in `Box`:
|
||||||
|
|
||||||
|
| Need | Use |
|
||||||
|
| ------------------------ | --------------------------------------- |
|
||||||
|
| Vertical stack of items | `Stack` (default) or `VStack` |
|
||||||
|
| Horizontal row | `HStack` or `Flex` |
|
||||||
|
| CSS Grid | `Grid` + `GridItem` |
|
||||||
|
| Equal-column grid | `SimpleGrid columns={N}` |
|
||||||
|
| Centered page content | `Container maxW="container.lg"` |
|
||||||
|
| Full flexbox control | `Flex` with explicit props |
|
||||||
|
| Semantic section/article | `Box as="section"` / `Box as="article"` |
|
||||||
|
|
||||||
|
Avoid deep nesting. If you're three `Box` levels deep with no semantic reason,
|
||||||
|
flatten it. Prefer `gap` over margin between siblings.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 3 — Use tokens, not raw values
|
||||||
|
|
||||||
|
Chakra v3 ships semantic tokens that automatically adapt to light/dark mode.
|
||||||
|
Prefer them over hard-coded palette values — they make the component theme-aware
|
||||||
|
without any extra work.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Prefer semantic tokens
|
||||||
|
<Box bg="bg.subtle" color="fg.default" borderColor="border.subtle" />
|
||||||
|
<Text color="fg.muted" />
|
||||||
|
<Box shadow="md" rounded="lg" />
|
||||||
|
|
||||||
|
// Use colorPalette for interactive components (not colorScheme)
|
||||||
|
<Button colorPalette="blue">Submit</Button>
|
||||||
|
<Badge colorPalette="green">Active</Badge>
|
||||||
|
```
|
||||||
|
|
||||||
|
Use raw palette values (`blue.500`, `gray.100`) only when a specific color is
|
||||||
|
intentional and should not shift with color mode.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 4 — Responsive styles
|
||||||
|
|
||||||
|
Chakra uses mobile-first breakpoints. Use array or object syntax consistently:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Array: [base, sm, md, lg, xl]
|
||||||
|
<Box px={[4, 6, 8]} fontSize={["sm", "md", "lg"]} />
|
||||||
|
|
||||||
|
// Object: explicit breakpoints
|
||||||
|
<SimpleGrid columns={{ base: 1, md: 2, lg: 3 }} gap={6} />
|
||||||
|
<Stack direction={{ base: "column", md: "row" }} gap={4} />
|
||||||
|
```
|
||||||
|
|
||||||
|
Every layout component should handle at least `base` (mobile) and `md` (desktop)
|
||||||
|
breakpoints unless the request is explicitly desktop-only.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 5 — Forms
|
||||||
|
|
||||||
|
Use `Field.Root` for all form fields — it wires up label, input, error, and help
|
||||||
|
text correctly:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Field.Root invalid={!!error} required>
|
||||||
|
<Field.Label>Email address</Field.Label>
|
||||||
|
<Input type="email" placeholder="you@example.com" />
|
||||||
|
<Field.ErrorText>{error}</Field.ErrorText>
|
||||||
|
<Field.HelpText>We'll never share your email.</Field.HelpText>
|
||||||
|
</Field.Root>
|
||||||
|
```
|
||||||
|
|
||||||
|
For form submission state, use `disabled` (not `isDisabled`) on inputs and
|
||||||
|
buttons. Group related fields in a `Stack gap={4}`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 6 — Accessibility
|
||||||
|
|
||||||
|
Chakra's built-in components handle most accessibility automatically — don't
|
||||||
|
override it. The things you do need to provide:
|
||||||
|
|
||||||
|
- **Icon-only buttons**: always add `aria-label`
|
||||||
|
```tsx
|
||||||
|
<IconButton aria-label="Close dialog" icon={<CloseIcon />} />
|
||||||
|
```
|
||||||
|
- **Images**: always pass meaningful `alt` text (or `alt=""` for decorative)
|
||||||
|
- **Form labels**: use `Field.Label` or ensure `htmlFor` matches the input `id`
|
||||||
|
- **Interactive custom elements**: if you build something with `onClick` on a
|
||||||
|
`Box`, use `as="button"` or an actual `<button>` so keyboard navigation works
|
||||||
|
- **Semantic headings**: use `h1`–`h6` hierarchy; don't skip levels
|
||||||
|
- **Color contrast**: don't use light gray text on white backgrounds; rely on
|
||||||
|
semantic tokens which are contrast-tested
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 7 — Next.js: where to add `"use client"`
|
||||||
|
|
||||||
|
In Next.js App Router, Server Components are the default. Add `"use client"`
|
||||||
|
only to files that need it — not to entire layouts or pages.
|
||||||
|
|
||||||
|
A component needs `"use client"` when it:
|
||||||
|
|
||||||
|
- Uses React hooks (`useState`, `useEffect`, `useContext`, etc.)
|
||||||
|
- Handles browser events (`onClick` with state, form submission, etc.)
|
||||||
|
- Uses browser APIs
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Server Component — no directive needed
|
||||||
|
export default function ProductCard({ name, price }: Props) {
|
||||||
|
return (
|
||||||
|
<Box p={4} borderWidth={1} rounded="md">
|
||||||
|
<Text fontWeight="bold">{name}</Text>
|
||||||
|
<Text color="fg.muted">{price}</Text>
|
||||||
|
</Box>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Client Component — needs the directive
|
||||||
|
;("use client")
|
||||||
|
export function AddToCartButton({ productId }: { productId: string }) {
|
||||||
|
const [added, setAdded] = useState(false)
|
||||||
|
return (
|
||||||
|
<Button onClick={() => setAdded(true)} colorPalette="blue">
|
||||||
|
{added ? "Added!" : "Add to cart"}
|
||||||
|
</Button>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The goal is to push interactivity to the leaves — keep as much of the tree as
|
||||||
|
Server Components as possible.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 8 — When to extract components, use recipes, and customize the theme
|
||||||
|
|
||||||
|
Extract a component when the same structure appears more than twice, or when a
|
||||||
|
piece is complex enough that naming it makes the parent clearer.
|
||||||
|
|
||||||
|
Suggest a **recipe** when a component has meaningful style variants that a
|
||||||
|
developer would want to customize. Suggest a **slot recipe** for components with
|
||||||
|
multiple coordinated parts (card with header/body/footer, stat with
|
||||||
|
label/value/icon, etc.).
|
||||||
|
|
||||||
|
For deeper theming work — defining brand color tokens, semantic tokens with dark
|
||||||
|
mode values, full recipe/slot-recipe authoring, typegen, or ejecting the default
|
||||||
|
theme — read `references/theming.md` before responding. It covers the complete
|
||||||
|
`defineConfig` / `createSystem` API with full examples.
|
||||||
|
|
||||||
|
For any chart request — bar charts, area charts, line charts, pie/donut charts,
|
||||||
|
`BarList`, `BarSegment`, or anything involving `@chakra-ui/charts` — read
|
||||||
|
`references/charts.md` before responding. It covers the `useChart` hook, all
|
||||||
|
three chart types, Recharts integration, color tokens, and complete runnable
|
||||||
|
examples.
|
||||||
|
|
||||||
|
When you're unsure which component to use, or the user hasn't specified one,
|
||||||
|
read `references/component-decision-tree.md`. It covers every Chakra component
|
||||||
|
with guidance on when to choose one over a similar alternative.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Output format
|
||||||
|
|
||||||
|
Produce:
|
||||||
|
|
||||||
|
1. **Complete, runnable code** — correct imports, no placeholders like `TODO` or
|
||||||
|
`...rest of component`
|
||||||
|
2. **Proper import statements** — group Chakra imports, then local imports
|
||||||
|
3. **Component separation** — split into multiple components/files if the
|
||||||
|
component is complex or contains clearly separable parts
|
||||||
|
4. **Responsive styles** — at minimum `base` and `md` breakpoints for layout
|
||||||
|
5. **Brief explanation after the code** — 2–4 sentences on the key decisions
|
||||||
|
made (layout approach, accessibility choices, responsive strategy). Skip the
|
||||||
|
explanation if the request was trivial.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Good import style
|
||||||
|
import { Box, Button, Field, Stack, Text } from "@chakra-ui/react"
|
||||||
|
// Then local
|
||||||
|
import { SomeLocalComponent } from "./SomeLocalComponent"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## When to ask first
|
||||||
|
|
||||||
|
Build immediately if the request is clear enough to produce something useful.
|
||||||
|
Ask first when:
|
||||||
|
|
||||||
|
- The data shape is unknown and it changes the entire structure (e.g., "build a
|
||||||
|
table" — how many columns? what data?)
|
||||||
|
- There are meaningful design choices the user might care about (layout
|
||||||
|
direction, number of columns, color palette)
|
||||||
|
- The user references files or existing components you haven't seen
|
||||||
|
|
||||||
|
When in doubt, state your assumptions at the top of the response and build —
|
||||||
|
it's faster for the user to redirect from something concrete than from nothing.
|
||||||
@@ -0,0 +1,461 @@
|
|||||||
|
# Chakra UI Charts Reference
|
||||||
|
|
||||||
|
Charts live in a separate package. Install it alongside `@chakra-ui/react`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# npm
|
||||||
|
npm install @chakra-ui/charts recharts
|
||||||
|
|
||||||
|
# pnpm
|
||||||
|
pnpm add @chakra-ui/charts recharts
|
||||||
|
|
||||||
|
# yarn
|
||||||
|
yarn add @chakra-ui/charts recharts
|
||||||
|
```
|
||||||
|
|
||||||
|
Imports come from `@chakra-ui/charts`, not `@chakra-ui/react`:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { BarList, BarSegment, Chart, useChart } from "@chakra-ui/charts"
|
||||||
|
import type { BarListData, BarSegmentData } from "@chakra-ui/charts"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Three chart types
|
||||||
|
|
||||||
|
| Component | Best for | Recharts? |
|
||||||
|
| ----------------------- | ---------------------------------------------- | --------- |
|
||||||
|
| `BarList` | Rankings, comparisons (horizontal bar per row) | No |
|
||||||
|
| `BarSegment` | Composition / parts of a whole (stacked bar) | No |
|
||||||
|
| `Chart.Root` + Recharts | Line, area, bar, pie, radar, and more | Yes |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## `useChart` — the core hook
|
||||||
|
|
||||||
|
Every chart starts with `useChart`. It processes data, resolves color tokens,
|
||||||
|
and provides utilities used throughout the chart's compound components.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
const chart = useChart({
|
||||||
|
data: [...], // array of data objects
|
||||||
|
series: [...], // which keys to plot and how to color them
|
||||||
|
sort: { by: "value", direction: "desc" }, // optional
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
**`series` items:**
|
||||||
|
|
||||||
|
```ts
|
||||||
|
{
|
||||||
|
name: keyof T // data key to read values from
|
||||||
|
color: ChartColor // Chakra token ("teal.solid") or CSS color ("#FF0000")
|
||||||
|
label?: ReactNode // display name in legend/tooltip (defaults to name)
|
||||||
|
stackId?: string // for stacking in Recharts charts
|
||||||
|
yAxisId?: string // for dual-axis charts
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Color type** — accepts any Chakra color token or CSS color:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
type ChartColor = Tokens["colors"] | CSSProperties["color"]
|
||||||
|
// "teal.solid" | "blue.subtle" | "red.500" | "#FF0000" | "hsl(...)"
|
||||||
|
```
|
||||||
|
|
||||||
|
**Useful return values:**
|
||||||
|
|
||||||
|
```ts
|
||||||
|
chart.data // sorted data array
|
||||||
|
chart.series // resolved series config
|
||||||
|
chart.color("teal.solid") // resolves token → CSS color
|
||||||
|
chart.key("revenue") // safe key accessor
|
||||||
|
chart.formatNumber({ notation: "compact" })(1234567) // "1.2M"
|
||||||
|
chart.formatDate({ month: "short" })("2024-01-15") // locale-aware
|
||||||
|
chart.getTotal("revenue") // sum all values
|
||||||
|
chart.getMin("revenue") / chart.getMax("revenue")
|
||||||
|
chart.getValuePercent("revenue", value) // % of total
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## BarList
|
||||||
|
|
||||||
|
Horizontal bar chart — one bar per data row. Good for leaderboards, traffic
|
||||||
|
sources, top items.
|
||||||
|
|
||||||
|
**Data shape:**
|
||||||
|
|
||||||
|
```ts
|
||||||
|
interface BarListData {
|
||||||
|
name: string // label shown on the bar
|
||||||
|
value: number // determines bar width
|
||||||
|
href?: string // optional link
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Basic example:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { BarList, type BarListData, useChart } from "@chakra-ui/charts"
|
||||||
|
|
||||||
|
const chart = useChart<BarListData>({
|
||||||
|
data: [
|
||||||
|
{ name: "Google", value: 1_200_000 },
|
||||||
|
{ name: "Direct", value: 840_000 },
|
||||||
|
{ name: "Twitter", value: 320_000 },
|
||||||
|
{ name: "LinkedIn", value: 95_000 },
|
||||||
|
],
|
||||||
|
sort: { by: "value", direction: "desc" },
|
||||||
|
series: [{ name: "name", color: "teal.subtle" }],
|
||||||
|
})
|
||||||
|
|
||||||
|
return (
|
||||||
|
<BarList.Root chart={chart}>
|
||||||
|
<BarList.Content>
|
||||||
|
<BarList.Label title="Source" flex="1">
|
||||||
|
<BarList.Bar tooltip />
|
||||||
|
</BarList.Label>
|
||||||
|
<BarList.Label title="Visits" titleAlignment="end">
|
||||||
|
<BarList.Value />
|
||||||
|
</BarList.Label>
|
||||||
|
</BarList.Content>
|
||||||
|
</BarList.Root>
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
**With a custom value formatter:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<BarList.Value valueFormatter={(v) => `${(v / 1000).toFixed(0)}K`} />
|
||||||
|
```
|
||||||
|
|
||||||
|
**With multiple value columns:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<BarList.Label title="Visits" minW="16" titleAlignment="end">
|
||||||
|
<BarList.Value />
|
||||||
|
</BarList.Label>
|
||||||
|
<BarList.Label title="%" minW="12" titleAlignment="end">
|
||||||
|
<BarList.Value
|
||||||
|
valueFormatter={(v) =>
|
||||||
|
`${chart.getValuePercent("value", v).toFixed(0)}%`
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</BarList.Label>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## BarSegment
|
||||||
|
|
||||||
|
Single horizontal bar broken into colored segments. Good for showing how a total
|
||||||
|
is split across categories (budget, traffic, inventory).
|
||||||
|
|
||||||
|
**Data shape:**
|
||||||
|
|
||||||
|
```ts
|
||||||
|
interface BarSegmentData {
|
||||||
|
name: string // segment label
|
||||||
|
value: number // determines segment width
|
||||||
|
color: string // Chakra color token for this segment
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Basic example:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { BarSegment, useChart } from "@chakra-ui/charts"
|
||||||
|
|
||||||
|
const chart = useChart({
|
||||||
|
data: [
|
||||||
|
{ name: "Google", value: 500_000, color: "teal.solid" },
|
||||||
|
{ name: "Direct", value: 300_000, color: "blue.solid" },
|
||||||
|
{ name: "Twitter", value: 150_000, color: "purple.solid" },
|
||||||
|
{ name: "LinkedIn", value: 50_000, color: "orange.solid" },
|
||||||
|
],
|
||||||
|
sort: { by: "value", direction: "desc" },
|
||||||
|
})
|
||||||
|
|
||||||
|
return (
|
||||||
|
<BarSegment.Root chart={chart}>
|
||||||
|
<BarSegment.Content>
|
||||||
|
<BarSegment.Value />
|
||||||
|
<BarSegment.Bar tooltip />
|
||||||
|
<BarSegment.Label />
|
||||||
|
</BarSegment.Content>
|
||||||
|
<BarSegment.Legend showPercent showValue />
|
||||||
|
</BarSegment.Root>
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
**With a reference line (e.g. target):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<BarSegment.Bar tooltip>
|
||||||
|
<BarSegment.Reference label="Target" value={600_000} />
|
||||||
|
</BarSegment.Bar>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Chart.Root + Recharts
|
||||||
|
|
||||||
|
Wrapper for any Recharts chart. Handles sizing, token resolution, and styled
|
||||||
|
tooltips and legends. You still compose the chart using standard Recharts
|
||||||
|
components — `BarChart`, `AreaChart`, `LineChart`, `PieChart`, etc.
|
||||||
|
|
||||||
|
### Bar chart
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { Chart, useChart } from "@chakra-ui/charts"
|
||||||
|
import {
|
||||||
|
Bar,
|
||||||
|
BarChart,
|
||||||
|
CartesianGrid,
|
||||||
|
Legend,
|
||||||
|
Tooltip,
|
||||||
|
XAxis,
|
||||||
|
YAxis,
|
||||||
|
} from "recharts"
|
||||||
|
|
||||||
|
const chart = useChart({
|
||||||
|
data: [
|
||||||
|
{ month: "Jan", revenue: 186, expenses: 80 },
|
||||||
|
{ month: "Feb", revenue: 165, expenses: 95 },
|
||||||
|
{ month: "Mar", revenue: 210, expenses: 110 },
|
||||||
|
],
|
||||||
|
series: [
|
||||||
|
{ name: "revenue", color: "teal.solid" },
|
||||||
|
{ name: "expenses", color: "orange.solid" },
|
||||||
|
],
|
||||||
|
})
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Chart.Root maxH="sm" chart={chart}>
|
||||||
|
<BarChart data={chart.data}>
|
||||||
|
<CartesianGrid stroke={chart.color("border.muted")} vertical={false} />
|
||||||
|
<XAxis dataKey={chart.key("month")} />
|
||||||
|
<YAxis />
|
||||||
|
<Tooltip cursor={false} content={<Chart.Tooltip />} />
|
||||||
|
<Legend content={<Chart.Legend />} />
|
||||||
|
{chart.series.map((item) => (
|
||||||
|
<Bar
|
||||||
|
key={item.name}
|
||||||
|
dataKey={chart.key(item.name)}
|
||||||
|
fill={chart.color(item.color)}
|
||||||
|
radius={4}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</BarChart>
|
||||||
|
</Chart.Root>
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Area chart
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { Area, AreaChart, CartesianGrid, Tooltip, XAxis } from "recharts"
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Chart.Root maxH="sm" chart={chart}>
|
||||||
|
<AreaChart data={chart.data}>
|
||||||
|
<defs>
|
||||||
|
{chart.series.map((item) => (
|
||||||
|
<Chart.Gradient
|
||||||
|
key={item.name}
|
||||||
|
id={item.name}
|
||||||
|
stops={[
|
||||||
|
{ offset: "0%", color: item.color, opacity: 0.2 },
|
||||||
|
{ offset: "100%", color: item.color, opacity: 0 },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</defs>
|
||||||
|
<CartesianGrid stroke={chart.color("border.muted")} vertical={false} />
|
||||||
|
<XAxis dataKey={chart.key("month")} />
|
||||||
|
<Tooltip cursor={false} content={<Chart.Tooltip />} />
|
||||||
|
{chart.series.map((item) => (
|
||||||
|
<Area
|
||||||
|
key={item.name}
|
||||||
|
dataKey={chart.key(item.name)}
|
||||||
|
stroke={chart.color(item.color)}
|
||||||
|
fill={`url(#${item.name})`}
|
||||||
|
stackId="a"
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</AreaChart>
|
||||||
|
</Chart.Root>
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Pie / donut chart
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { Pie, PieChart, Tooltip } from "recharts"
|
||||||
|
|
||||||
|
const chart = useChart({
|
||||||
|
data: [
|
||||||
|
{ browser: "Chrome", visitors: 275, color: "teal.solid" },
|
||||||
|
{ browser: "Safari", visitors: 200, color: "blue.solid" },
|
||||||
|
{ browser: "Firefox", visitors: 120, color: "orange.solid" },
|
||||||
|
{ browser: "Edge", visitors: 80, color: "purple.solid" },
|
||||||
|
],
|
||||||
|
series: [{ name: "visitors" }],
|
||||||
|
})
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Chart.Root maxH="sm" chart={chart}>
|
||||||
|
<PieChart>
|
||||||
|
<Tooltip content={<Chart.Tooltip hideLabel />} />
|
||||||
|
<Pie
|
||||||
|
data={chart.data}
|
||||||
|
dataKey={chart.key("visitors")}
|
||||||
|
nameKey={chart.key("browser")}
|
||||||
|
innerRadius="60%" // remove for a filled pie
|
||||||
|
paddingAngle={2}
|
||||||
|
>
|
||||||
|
{chart.data.map((item, index) => (
|
||||||
|
<Cell key={index} fill={chart.color(item.color)} />
|
||||||
|
))}
|
||||||
|
{/* Center text for donut */}
|
||||||
|
<Label
|
||||||
|
content={
|
||||||
|
<Chart.RadialText
|
||||||
|
viewBox={undefined}
|
||||||
|
title={chart.getTotal("visitors").toLocaleString()}
|
||||||
|
description="Total visitors"
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
position="center"
|
||||||
|
/>
|
||||||
|
</Pie>
|
||||||
|
</PieChart>
|
||||||
|
</Chart.Root>
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Chart sub-components
|
||||||
|
|
||||||
|
### `Chart.Tooltip`
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Tooltip
|
||||||
|
cursor={false}
|
||||||
|
content={
|
||||||
|
<Chart.Tooltip
|
||||||
|
showTotal // show sum of all series at bottom
|
||||||
|
hideLabel // hide the x-axis label row
|
||||||
|
hideSeriesLabel // hide series names
|
||||||
|
indicator="line" // "dot" | "line" | "dashed"
|
||||||
|
formatter={(value, name) => [`$${value}`, name]}
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
```
|
||||||
|
|
||||||
|
### `Chart.Legend`
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Legend
|
||||||
|
content={
|
||||||
|
<Chart.Legend
|
||||||
|
title="Channels"
|
||||||
|
interaction="click" // "hover" (default) | "click"
|
||||||
|
verticalAlign="top" // "top" | "bottom" (default)
|
||||||
|
align="right" // "left" | "center" (default) | "right"
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
```
|
||||||
|
|
||||||
|
Legend interaction highlights/dims series on hover or click.
|
||||||
|
|
||||||
|
### `Chart.Gradient`
|
||||||
|
|
||||||
|
Defines an SVG gradient for area fills. Must be inside a `<defs>` block:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<defs>
|
||||||
|
<Chart.Gradient
|
||||||
|
id="revenue-gradient"
|
||||||
|
stops={[
|
||||||
|
{ offset: "0%", color: "teal.solid", opacity: 0.3 },
|
||||||
|
{ offset: "100%", color: "teal.solid", opacity: 0 },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</defs>
|
||||||
|
|
||||||
|
<Area fill="url(#revenue-gradient)" ... />
|
||||||
|
```
|
||||||
|
|
||||||
|
### `Chart.RadialText`
|
||||||
|
|
||||||
|
Centers a title + description inside a pie or donut chart:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Label
|
||||||
|
content={
|
||||||
|
<Chart.RadialText
|
||||||
|
viewBox={undefined}
|
||||||
|
title="$1.2M"
|
||||||
|
description="Total revenue"
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
position="center"
|
||||||
|
/>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Colors and theming
|
||||||
|
|
||||||
|
All chart colors accept Chakra token strings or plain CSS colors:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// Chakra semantic tokens — respond to light/dark mode
|
||||||
|
color: "teal.solid"
|
||||||
|
color: "blue.subtle"
|
||||||
|
color: "border.muted" // useful for grid lines
|
||||||
|
|
||||||
|
// Palette steps
|
||||||
|
color: "blue.500"
|
||||||
|
|
||||||
|
// Raw CSS
|
||||||
|
color: "#3b82f6"
|
||||||
|
color: "hsl(210, 100%, 56%)"
|
||||||
|
```
|
||||||
|
|
||||||
|
Use `chart.color(token)` to resolve a token to a CSS value wherever Recharts
|
||||||
|
needs a string (e.g. `fill`, `stroke`, `CartesianGrid stroke`).
|
||||||
|
|
||||||
|
Recommended color tokens for multi-series charts:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
series: [
|
||||||
|
{ name: "a", color: "teal.solid" },
|
||||||
|
{ name: "b", color: "blue.solid" },
|
||||||
|
{ name: "c", color: "purple.solid" },
|
||||||
|
{ name: "d", color: "orange.solid" },
|
||||||
|
{ name: "e", color: "red.solid" },
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Output format
|
||||||
|
|
||||||
|
When building chart components:
|
||||||
|
|
||||||
|
1. Show the `useChart` setup and data shape first
|
||||||
|
2. Produce complete, runnable JSX with correct imports from both
|
||||||
|
`@chakra-ui/charts` and `recharts`
|
||||||
|
3. Use `chart.color("border.muted")` for grid lines so they respect dark mode
|
||||||
|
4. Default `Chart.Root` to `maxH="sm"` unless the user specifies a size
|
||||||
|
5. Include a `Tooltip` with `<Chart.Tooltip />` on every chart — it's almost
|
||||||
|
always wanted
|
||||||
|
6. Note the install command if the project doesn't already have
|
||||||
|
`@chakra-ui/charts`
|
||||||
@@ -0,0 +1,287 @@
|
|||||||
|
# Chakra UI Component Decision Tree
|
||||||
|
|
||||||
|
When the user hasn't specified a component, choose the most appropriate one
|
||||||
|
based on the guidelines below. Prefer an existing Chakra component over a custom
|
||||||
|
implementation. Match the interaction model first, then the visual treatment.
|
||||||
|
Prefer the narrowest component that fits — don't reach for `Box` when a more
|
||||||
|
specific primitive exists.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Layout and structure
|
||||||
|
|
||||||
|
- Use `Stack` (or `VStack`) for a vertical sequence of elements with consistent
|
||||||
|
spacing.
|
||||||
|
- Use `HStack` for a horizontal sequence of elements with consistent spacing.
|
||||||
|
- Use `Flex` when you need explicit control over flexbox properties (direction,
|
||||||
|
wrap, alignment).
|
||||||
|
- Use `Grid` + `GridItem` for two-dimensional layouts (rows and columns).
|
||||||
|
- Use `SimpleGrid` for equal-width columns that wrap automatically — good for
|
||||||
|
card grids and dashboards.
|
||||||
|
- Use `Container` to constrain page content to a max-width with horizontal
|
||||||
|
centering.
|
||||||
|
- Use `Center` to center content both horizontally and vertically without manual
|
||||||
|
flex setup.
|
||||||
|
- Use `AbsoluteCenter` when centering with `position: absolute` — useful for
|
||||||
|
overlays and loaders.
|
||||||
|
- Use `Card` when content is a self-contained unit that needs visual separation
|
||||||
|
(border, shadow, padding). Use `Box` only when no built-in container semantics
|
||||||
|
apply.
|
||||||
|
- Use `Wrap` for tag clouds, badge sets, or button groups that should flow and
|
||||||
|
wrap automatically.
|
||||||
|
- Use `Spacer` inside `Flex` to push elements to opposite ends.
|
||||||
|
- Use `Group` to visually merge related elements (buttons, inputs) into a single
|
||||||
|
bordered unit.
|
||||||
|
- Use `Bleed` to extend a background or image beyond the padding of its parent
|
||||||
|
container.
|
||||||
|
- Use `Splitter` when the user should be able to resize two adjacent panels.
|
||||||
|
- Use `ScrollArea` for a container that needs custom cross-browser styled
|
||||||
|
scrollbars.
|
||||||
|
- Use `AspectRatio` to lock a child element (video, image, map) to a fixed
|
||||||
|
aspect ratio.
|
||||||
|
|
||||||
|
### Stack vs Flex vs Grid
|
||||||
|
|
||||||
|
- Choose `Stack` or `HStack`/`VStack` for uniform spacing along one axis — it's
|
||||||
|
the most common case.
|
||||||
|
- Choose `Flex` when you need `flexWrap`, `justifyContent`, `alignItems`, or
|
||||||
|
other flex properties beyond spacing.
|
||||||
|
- Choose `Grid` when you need to position elements across both rows and columns
|
||||||
|
at the same time.
|
||||||
|
- Choose `SimpleGrid` when you only need responsive equal-width columns and
|
||||||
|
nothing more.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Typography
|
||||||
|
|
||||||
|
- Use `Heading` for page and section titles (`h1`–`h6`). Don't use `Text` as a
|
||||||
|
heading shortcut.
|
||||||
|
- Use `Text` for body copy, labels, and descriptive text.
|
||||||
|
- Use `Span` for inline styled text inside a paragraph.
|
||||||
|
- Use `Em` and `Strong` for semantically emphasized or important text.
|
||||||
|
- Use `Mark` for highlighted text (e.g. search result matches).
|
||||||
|
- Use `Code` for short inline code snippets.
|
||||||
|
- Use `CodeBlock` for multi-line code with copy button and optional collapse —
|
||||||
|
not for single-line snippets.
|
||||||
|
- Use `Kbd` to display keyboard shortcuts.
|
||||||
|
- Use `Blockquote` for pull quotes with attribution.
|
||||||
|
- Use `Highlight` to highlight matching substrings dynamically in text.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Actions and links
|
||||||
|
|
||||||
|
- Use `Button` for primary and secondary actions (form submissions,
|
||||||
|
confirmations, key page actions).
|
||||||
|
- Use `IconButton` for icon-only actions — always provide `aria-label`.
|
||||||
|
- Use `CloseButton` for dismiss/close actions in dialogs, drawers, and toasts.
|
||||||
|
- Use `ButtonGroup` to group related actions (e.g. Save / Cancel) with
|
||||||
|
consistent sizing and variant.
|
||||||
|
- Use `Link` for text navigation — inline within a sentence or standalone. Use
|
||||||
|
`asChild` with Next.js `<Link>` in App Router projects.
|
||||||
|
- Use `LinkBox` + `LinkOverlay` to make an entire card or row clickable while
|
||||||
|
preserving accessible markup.
|
||||||
|
- Use `Toggle` when a button should visually represent an on/off pressed state.
|
||||||
|
- Use `Switch` (not `Toggle`) when the interaction is a persistent on/off
|
||||||
|
setting (e.g. enable notifications).
|
||||||
|
- Use `DownloadTrigger` for file download buttons.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Choosing from options
|
||||||
|
|
||||||
|
- Use `Switch` for turning a single setting on or off.
|
||||||
|
- Use `Checkbox` for a single independent yes/no option. Use `CheckboxGroup` for
|
||||||
|
a set of independent options where many can be selected.
|
||||||
|
- Use `CheckboxCard` over `Checkbox` when the option needs a title, description,
|
||||||
|
or more visual emphasis.
|
||||||
|
- Use `RadioGroup` for mutually exclusive options when 2–4 options should always
|
||||||
|
be visible.
|
||||||
|
- Use `RadioCard` over `RadioGroup` when each option benefits from a
|
||||||
|
description, icon, or richer presentation.
|
||||||
|
- Use `SegmentGroup` for a compact mutually exclusive mode/view switch
|
||||||
|
(iOS-style segmented control) — typically 2–4 options.
|
||||||
|
- Use `NativeSelect` for mobile-first dropdowns where the platform picker is
|
||||||
|
preferred.
|
||||||
|
- Use `Select` for styled dropdowns with full design control — prefer over
|
||||||
|
`NativeSelect` on desktop.
|
||||||
|
- Use `Combobox` when the user should type to filter a long list or search
|
||||||
|
options — prefer over `Select` for lists longer than ~15 items.
|
||||||
|
- Use `Listbox` when options must always be visible and scrollable without a
|
||||||
|
dropdown trigger.
|
||||||
|
- Use `TagsInput` for entering multiple free-form or autocompleted values
|
||||||
|
(skills, labels, emails).
|
||||||
|
- Use `RatingGroup` for star or point ratings.
|
||||||
|
|
||||||
|
### Select vs Combobox vs NativeSelect
|
||||||
|
|
||||||
|
- Choose `NativeSelect` for mobile-first or form-heavy interfaces where native
|
||||||
|
picker behavior is expected.
|
||||||
|
- Choose `Select` for styled dropdowns on desktop with a known, bounded list.
|
||||||
|
- Choose `Combobox` when filtering/searching is important or the list is long.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Text and value input
|
||||||
|
|
||||||
|
- Use `Input` for single-line plain text.
|
||||||
|
- Use `Textarea` for multi-line text.
|
||||||
|
- Use `NumberInput` for numeric entry with increment/decrement controls.
|
||||||
|
- Use `Slider` for adjusting a value when direct manipulation is preferred over
|
||||||
|
exact entry. Use a range slider (dual thumbs) for min/max ranges.
|
||||||
|
- Use `PinInput` for fixed-length codes — OTP verification, PIN entry. It
|
||||||
|
auto-advances focus between fields.
|
||||||
|
- Use `Editable` for click-to-edit inline text — useful for titles,
|
||||||
|
descriptions, and table cells.
|
||||||
|
- Use `DatePicker` when a calendar popover should assist with date selection.
|
||||||
|
- Use `ColorPicker` for full color selection with RGB/HSL/hex modes and
|
||||||
|
eyedropper.
|
||||||
|
- Use `FileUpload` for file selection with drag-and-drop and preview.
|
||||||
|
- Use `Clipboard` for copy-to-clipboard functionality with visual feedback.
|
||||||
|
- Use `Field.Root` to wrap every form input — it wires up the label, helper
|
||||||
|
text, error text, and required indicator correctly.
|
||||||
|
- Use `InputGroup` to attach prefix/suffix addons (icons, currency symbols,
|
||||||
|
units) to an `Input`.
|
||||||
|
- Use `Fieldset` to group semantically related form fields under a shared
|
||||||
|
legend.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Overlays and pop-ups
|
||||||
|
|
||||||
|
- Use `Tooltip` for a short text description of a focusable element. Don't put
|
||||||
|
interactive content in a tooltip.
|
||||||
|
- Use `HoverCard` for richer preview content on hover (user profiles, link
|
||||||
|
previews) — more than a tooltip, less than a popover.
|
||||||
|
- Use `Popover` for interactive contextual content anchored to a trigger —
|
||||||
|
forms, filters, settings panels.
|
||||||
|
- Use `Dialog` for modal tasks that require user attention before continuing.
|
||||||
|
- Use `Drawer` for off-canvas panels — navigation, detail views, settings — when
|
||||||
|
modal behavior is needed but the content is beside rather than over the page.
|
||||||
|
- Use `Toast` for brief transient feedback after an action (saved, error,
|
||||||
|
copied). Use the `Toaster` component to render stacked toasts.
|
||||||
|
- Use `ActionBar` for mobile-style bulk action bars that appear after selection.
|
||||||
|
- Use `Menu` for action menus triggered by a button — "more options",
|
||||||
|
right-click menus. Use `Menu.CheckboxItem` and `Menu.RadioItem` for
|
||||||
|
toggle/selection actions within a menu.
|
||||||
|
|
||||||
|
### Tooltip vs HoverCard vs Popover
|
||||||
|
|
||||||
|
- Choose `Tooltip` for a single line of non-interactive help text.
|
||||||
|
- Choose `HoverCard` for hover-triggered preview cards with structured content.
|
||||||
|
- Choose `Popover` when the floating content needs to be interactive (has
|
||||||
|
buttons, inputs, or links).
|
||||||
|
|
||||||
|
### Dialog vs Drawer
|
||||||
|
|
||||||
|
- Choose `Dialog` when the overlay should be centered, blocking, and focus
|
||||||
|
attention on a specific task or confirmation.
|
||||||
|
- Choose `Drawer` when the content slides in from an edge and relates to what's
|
||||||
|
already on screen (details, navigation, filters).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Disclosure and navigation
|
||||||
|
|
||||||
|
- Use `Accordion` for a set of related collapsible sections where only one (or a
|
||||||
|
few) should be open at a time — FAQs, grouped settings.
|
||||||
|
- Use `Collapsible` for a single expandable section — don't use `Accordion` with
|
||||||
|
one item.
|
||||||
|
- Use `Tabs` for peer content panels where switching shows one panel at a time —
|
||||||
|
prefer for horizontal layouts.
|
||||||
|
- Use `SegmentGroup` instead of `Tabs` when switching modes or views rather than
|
||||||
|
showing different full content panels.
|
||||||
|
- Use `Steps` for multi-step wizards and onboarding flows — shows progress and
|
||||||
|
allows back/next navigation.
|
||||||
|
- Use `Breadcrumb` to show the user's location in a hierarchy.
|
||||||
|
- Use `Pagination` for navigating paged datasets.
|
||||||
|
- Use `Menu` for dropdown navigation menus.
|
||||||
|
- Use `TreeView` when a file-system-style hierarchy must stay visible and
|
||||||
|
expandable in place.
|
||||||
|
|
||||||
|
### Accordion vs Tabs vs Collapsible
|
||||||
|
|
||||||
|
- Choose `Accordion` for vertically stacked collapsible sections (FAQs, settings
|
||||||
|
groups).
|
||||||
|
- Choose `Tabs` for horizontal peer sections where all tabs are always visible.
|
||||||
|
- Choose `Collapsible` for a single show/hide section — not a group.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Data display
|
||||||
|
|
||||||
|
- Use `Table` for structured tabular data with rows and columns — sortable
|
||||||
|
headers, dense comparison.
|
||||||
|
- Use `DataList` for key-value pairs (user profile details, metadata) — not true
|
||||||
|
tabular data.
|
||||||
|
- Use `Stat` + `StatGroup` for KPI metrics and dashboard numbers with up/down
|
||||||
|
indicators.
|
||||||
|
- Use `Timeline` for chronological events, changelogs, or process steps.
|
||||||
|
- Use `Badge` for compact non-removable status labels (Active, Beta, New).
|
||||||
|
- Use `Tag` over `Badge` when the label should be removable or interactive.
|
||||||
|
- Use `Avatar` + `AvatarGroup` for user profile pictures with fallback initials
|
||||||
|
or icon.
|
||||||
|
- Use `Carousel` for image galleries, feature showcases, or content sliders.
|
||||||
|
- Use `QrCode` to render a QR code from a string value.
|
||||||
|
- Use `ColorSwatch` to display a color value visually.
|
||||||
|
|
||||||
|
### Table vs DataList
|
||||||
|
|
||||||
|
- Choose `Table` when data has multiple comparable columns and rows.
|
||||||
|
- Choose `DataList` for a single record's attributes displayed as label/value
|
||||||
|
pairs.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Feedback and status
|
||||||
|
|
||||||
|
- Use `Alert` for persistent in-page messages (warnings, info, errors) that are
|
||||||
|
part of the page layout.
|
||||||
|
- Use `Toast` for transient post-action feedback — it disappears automatically.
|
||||||
|
- Use `EmptyState` for no-data and no-results states — provides structured
|
||||||
|
layout for illustration, title, description, and actions.
|
||||||
|
- Use `Spinner` for indeterminate loading — content is fetching, duration
|
||||||
|
unknown.
|
||||||
|
- Use `Skeleton` for loading placeholders that approximate the shape of incoming
|
||||||
|
content.
|
||||||
|
- Use `Progress` for a linear progress bar on an operation with a known
|
||||||
|
completion percentage.
|
||||||
|
- Use `ProgressCircle` for the same use case when a circular indicator fits the
|
||||||
|
layout better.
|
||||||
|
- Use `Loader` as an alternative to `Spinner` for a different visual style of
|
||||||
|
indeterminate loading.
|
||||||
|
|
||||||
|
### Alert vs Toast vs EmptyState
|
||||||
|
|
||||||
|
- Choose `Alert` when the message is persistent and tied to content on the
|
||||||
|
current view.
|
||||||
|
- Choose `Toast` when the message is temporary and triggered by a user action.
|
||||||
|
- Choose `EmptyState` when there is no content to display and you want to
|
||||||
|
explain why and offer a next action.
|
||||||
|
|
||||||
|
### Spinner vs Skeleton vs Progress
|
||||||
|
|
||||||
|
- Choose `Spinner` when loading is happening and the layout isn't known yet.
|
||||||
|
- Choose `Skeleton` when the layout is known — show placeholder shapes that
|
||||||
|
match the expected content.
|
||||||
|
- Choose `Progress` when the operation has a measurable percentage.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Utilities
|
||||||
|
|
||||||
|
- Use `VisuallyHidden` for screen-reader-only text — skip links, icon button
|
||||||
|
labels added outside the button.
|
||||||
|
- Use `SkipNav` to add a skip-to-main-content accessibility link.
|
||||||
|
- Use `Portal` when a component must render outside its DOM parent to avoid
|
||||||
|
z-index or overflow clipping issues.
|
||||||
|
- Use `FocusTrap` to constrain keyboard focus within a region (custom modals,
|
||||||
|
custom drawers).
|
||||||
|
- Use `Presence` to animate components on mount and unmount.
|
||||||
|
- Use `Show` / `Hide` for responsive conditional rendering based on breakpoints.
|
||||||
|
- Use `For` as a typed loop utility when rendering lists of components.
|
||||||
|
- Use `ClientOnly` to prevent SSR hydration mismatches for browser-only content.
|
||||||
|
- Use `FormatNumber` / `FormatByte` for locale-aware number and file-size
|
||||||
|
formatting.
|
||||||
|
- Use `Marquee` for scrolling announcement banners or news tickers.
|
||||||
@@ -0,0 +1,331 @@
|
|||||||
|
# Chakra UI Theming Reference
|
||||||
|
|
||||||
|
Use v3 patterns (`defineConfig`, `createSystem`, `defineRecipe`,
|
||||||
|
`defineSlotRecipe`) by default. Only use v2 patterns (`extendTheme`,
|
||||||
|
`styleConfig`) if the project is explicitly on v2.
|
||||||
|
|
||||||
|
Before starting, check `package.json` for the Chakra UI version and look for an
|
||||||
|
existing theme file (`theme.ts`, `system.ts`) to understand what's already
|
||||||
|
defined.
|
||||||
|
|
||||||
|
Clarify scope when needed:
|
||||||
|
|
||||||
|
- **Full design system** — tokens, semantic tokens, and component recipes from
|
||||||
|
scratch
|
||||||
|
- **Partial update** — adding or changing specific tokens or recipes
|
||||||
|
- **Single recipe** — one component's styles with variants
|
||||||
|
- **Typegen only** — running `@chakra-ui/cli typegen` after custom additions
|
||||||
|
|
||||||
|
If the user says "add my brand colors" without specifying the colors, ask first.
|
||||||
|
A partial answer is worse than pausing to clarify.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## System setup: `defineConfig` and `createSystem`
|
||||||
|
|
||||||
|
All theming in v3 starts with `createSystem`. Use `defineConfig` to author
|
||||||
|
customizations, then merge with `defaultConfig`:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// theme.ts
|
||||||
|
import { createSystem, defaultConfig, defineConfig } from "@chakra-ui/react"
|
||||||
|
|
||||||
|
const config = defineConfig({
|
||||||
|
theme: {
|
||||||
|
tokens: {
|
||||||
|
/* ... */
|
||||||
|
},
|
||||||
|
semanticTokens: {
|
||||||
|
/* ... */
|
||||||
|
},
|
||||||
|
recipes: {
|
||||||
|
/* ... */
|
||||||
|
},
|
||||||
|
slotRecipes: {
|
||||||
|
/* ... */
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
export const system = createSystem(defaultConfig, config)
|
||||||
|
```
|
||||||
|
|
||||||
|
Pass `system` to `ChakraProvider`:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// components/ui/provider.tsx
|
||||||
|
"use client"
|
||||||
|
import { system } from "@/theme"
|
||||||
|
import { ChakraProvider } from "@chakra-ui/react"
|
||||||
|
|
||||||
|
export function Provider({ children }) {
|
||||||
|
return <ChakraProvider value={system}>{children}</ChakraProvider>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Tokens
|
||||||
|
|
||||||
|
Tokens are the raw, concrete values in your design system — the foundation
|
||||||
|
everything else references.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
const config = defineConfig({
|
||||||
|
theme: {
|
||||||
|
tokens: {
|
||||||
|
colors: {
|
||||||
|
brand: {
|
||||||
|
50: { value: "#eff6ff" },
|
||||||
|
100: { value: "#dbeafe" },
|
||||||
|
200: { value: "#bfdbfe" },
|
||||||
|
500: { value: "#3b82f6" },
|
||||||
|
600: { value: "#2563eb" },
|
||||||
|
700: { value: "#1d4ed8" },
|
||||||
|
900: { value: "#1e3a8a" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
fonts: {
|
||||||
|
heading: { value: "var(--font-geist-sans), sans-serif" },
|
||||||
|
body: { value: "var(--font-geist-sans), sans-serif" },
|
||||||
|
mono: { value: "var(--font-geist-mono), monospace" },
|
||||||
|
},
|
||||||
|
fontSizes: {
|
||||||
|
xs: { value: "0.75rem" },
|
||||||
|
sm: { value: "0.875rem" },
|
||||||
|
md: { value: "1rem" },
|
||||||
|
lg: { value: "1.125rem" },
|
||||||
|
xl: { value: "1.25rem" },
|
||||||
|
"2xl": { value: "1.5rem" },
|
||||||
|
},
|
||||||
|
radii: {
|
||||||
|
sm: { value: "0.25rem" },
|
||||||
|
md: { value: "0.375rem" },
|
||||||
|
lg: { value: "0.5rem" },
|
||||||
|
xl: { value: "0.75rem" },
|
||||||
|
full: { value: "9999px" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Use scale-based keys for palettes (`50`, `100`, …, `900`) and semantic keys for
|
||||||
|
single values (`sm`, `md`, `lg`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Semantic tokens
|
||||||
|
|
||||||
|
Semantic tokens reference base tokens and assign _meaning_ to them. Their key
|
||||||
|
feature: different values per color mode, making dark mode automatic.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
const config = defineConfig({
|
||||||
|
theme: {
|
||||||
|
semanticTokens: {
|
||||||
|
colors: {
|
||||||
|
"brand.solid": {
|
||||||
|
value: { base: "{colors.brand.600}", _dark: "{colors.brand.400}" },
|
||||||
|
},
|
||||||
|
"brand.muted": {
|
||||||
|
value: { base: "{colors.brand.100}", _dark: "{colors.brand.900}" },
|
||||||
|
},
|
||||||
|
"brand.subtle": {
|
||||||
|
value: { base: "{colors.brand.50}", _dark: "{colors.brand.950}" },
|
||||||
|
},
|
||||||
|
|
||||||
|
"bg.default": { value: { base: "white", _dark: "{colors.gray.900}" } },
|
||||||
|
"bg.subtle": {
|
||||||
|
value: { base: "{colors.gray.50}", _dark: "{colors.gray.800}" },
|
||||||
|
},
|
||||||
|
"bg.muted": {
|
||||||
|
value: { base: "{colors.gray.100}", _dark: "{colors.gray.700}" },
|
||||||
|
},
|
||||||
|
|
||||||
|
"fg.default": { value: { base: "{colors.gray.900}", _dark: "white" } },
|
||||||
|
"fg.muted": {
|
||||||
|
value: { base: "{colors.gray.600}", _dark: "{colors.gray.400}" },
|
||||||
|
},
|
||||||
|
"fg.subtle": {
|
||||||
|
value: { base: "{colors.gray.400}", _dark: "{colors.gray.600}" },
|
||||||
|
},
|
||||||
|
|
||||||
|
"border.default": {
|
||||||
|
value: { base: "{colors.gray.200}", _dark: "{colors.gray.700}" },
|
||||||
|
},
|
||||||
|
"border.muted": {
|
||||||
|
value: { base: "{colors.gray.100}", _dark: "{colors.gray.800}" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Components that use `bg="bg.subtle"` instead of `bg="gray.50"` automatically get
|
||||||
|
the correct dark mode value — no conditional logic needed. Build on semantic
|
||||||
|
tokens wherever possible.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Recipes (single-component styles)
|
||||||
|
|
||||||
|
Recipes replace `styleConfig` from v2. Use them when a single component has
|
||||||
|
meaningful style variants that developers will reuse across the project.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { defineRecipe } from "@chakra-ui/react"
|
||||||
|
|
||||||
|
export const badgeRecipe = defineRecipe({
|
||||||
|
base: {
|
||||||
|
display: "inline-flex",
|
||||||
|
alignItems: "center",
|
||||||
|
px: 2,
|
||||||
|
py: 0.5,
|
||||||
|
borderRadius: "full",
|
||||||
|
fontSize: "xs",
|
||||||
|
fontWeight: "medium",
|
||||||
|
},
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
solid: { bg: "colorPalette.500", color: "white" },
|
||||||
|
subtle: { bg: "colorPalette.100", color: "colorPalette.800" },
|
||||||
|
outline: {
|
||||||
|
borderWidth: 1,
|
||||||
|
borderColor: "colorPalette.500",
|
||||||
|
color: "colorPalette.600",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
size: {
|
||||||
|
sm: { px: 1.5, py: 0.5, fontSize: "2xs" },
|
||||||
|
md: { px: 2, py: 0.5, fontSize: "xs" },
|
||||||
|
lg: { px: 3, py: 1, fontSize: "sm" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: { variant: "subtle", size: "md" },
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Register in the theme config:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
const config = defineConfig({ theme: { recipes: { badge: badgeRecipe } } })
|
||||||
|
```
|
||||||
|
|
||||||
|
`colorPalette` inside a recipe is a placeholder — it resolves to whatever
|
||||||
|
`colorPalette` prop the consumer passes (`colorPalette="blue"` → `blue.500`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Slot recipes (multi-part components)
|
||||||
|
|
||||||
|
Slot recipes replace `multiStyleConfig` from v2. Use them when a component has
|
||||||
|
multiple coordinated parts that all respond to the same variants.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { defineSlotRecipe } from "@chakra-ui/react"
|
||||||
|
|
||||||
|
export const cardSlotRecipe = defineSlotRecipe({
|
||||||
|
slots: ["root", "header", "body", "footer", "title"],
|
||||||
|
base: {
|
||||||
|
root: { bg: "bg.surface", rounded: "xl", overflow: "hidden", shadow: "sm" },
|
||||||
|
header: { px: 6, py: 4, borderBottomWidth: 1, borderColor: "border.muted" },
|
||||||
|
body: { px: 6, py: 4 },
|
||||||
|
footer: { px: 6, py: 4, borderTopWidth: 1, borderColor: "border.muted" },
|
||||||
|
title: { fontSize: "lg", fontWeight: "semibold", color: "fg.default" },
|
||||||
|
},
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
elevated: { root: { shadow: "md" } },
|
||||||
|
outline: {
|
||||||
|
root: { shadow: "none", borderWidth: 1, borderColor: "border.default" },
|
||||||
|
},
|
||||||
|
filled: { root: { bg: "bg.subtle", shadow: "none" } },
|
||||||
|
},
|
||||||
|
size: {
|
||||||
|
sm: {
|
||||||
|
root: { rounded: "lg" },
|
||||||
|
body: { px: 4, py: 3 },
|
||||||
|
header: { px: 4, py: 3 },
|
||||||
|
},
|
||||||
|
md: {},
|
||||||
|
lg: { body: { px: 8, py: 6 }, header: { px: 8, py: 6 } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: { variant: "elevated", size: "md" },
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Register:
|
||||||
|
`const config = defineConfig({ theme: { slotRecipes: { card: cardSlotRecipe } } })`
|
||||||
|
|
||||||
|
Consume with `useSlotRecipe`:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { useSlotRecipe } from "@chakra-ui/react"
|
||||||
|
|
||||||
|
function Card({ variant = "elevated", size = "md", children }) {
|
||||||
|
const recipe = useSlotRecipe({ key: "card" })
|
||||||
|
const styles = recipe({ variant, size })
|
||||||
|
return <Box css={styles.root}>{children}</Box>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Typegen
|
||||||
|
|
||||||
|
Run typegen after adding custom tokens, semantic tokens, recipes, or slot
|
||||||
|
recipes. Without it, TypeScript won't know your custom values exist.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx @chakra-ui/cli typegen ./theme.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
| Flag | Effect |
|
||||||
|
| ------------------- | ------------------------------------------------------------- |
|
||||||
|
| `--strict` | Strict literal types for variant and size props (recommended) |
|
||||||
|
| `--watch` | Re-runs automatically whenever the theme file changes |
|
||||||
|
| `--outdir <dir>` | Custom output directory for generated types |
|
||||||
|
| `--tsconfig <path>` | Path to tsconfig when using path aliases |
|
||||||
|
|
||||||
|
For active development: `npx @chakra-ui/cli typegen ./theme.ts --watch`
|
||||||
|
|
||||||
|
Typegen is required when you've added custom color tokens, semantic tokens,
|
||||||
|
spacing/font/radius tokens, or new recipes or slot recipes.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Ejecting the default theme
|
||||||
|
|
||||||
|
For full control over Chakra's built-in tokens, recipes, and styles:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx @chakra-ui/cli eject
|
||||||
|
```
|
||||||
|
|
||||||
|
Writes the complete default theme into a `theme/` directory (`--outdir <dir>` to
|
||||||
|
override), including separate files for tokens, semantic tokens, recipes, slot
|
||||||
|
recipes, text styles, layer styles, and animation styles — all as editable
|
||||||
|
`defineConfig` exports.
|
||||||
|
|
||||||
|
Use `eject` when modifying built-in component recipes or replacing large parts
|
||||||
|
of the default token scale. For smaller customizations (adding brand colors,
|
||||||
|
overriding a few tokens), extending with `defineConfig` is simpler.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Output format
|
||||||
|
|
||||||
|
Produce:
|
||||||
|
|
||||||
|
1. **Complete theme config** — `defineConfig` with all relevant sections
|
||||||
|
2. **Proper imports** — `defineConfig`, `createSystem`, `defineRecipe`, etc.
|
||||||
|
from `@chakra-ui/react`
|
||||||
|
3. **Provider wiring** — how to pass `system` to `ChakraProvider` if needed
|
||||||
|
4. **Usage examples** — show tokens/recipes consumed in a component
|
||||||
|
5. **Typegen reminder** — note when to run typegen
|
||||||
|
|
||||||
|
Brief explanation after the code (2–4 sentences) on key decisions. Skip for
|
||||||
|
trivial requests.
|
||||||
@@ -0,0 +1,494 @@
|
|||||||
|
---
|
||||||
|
name: chakra-ui-migrate
|
||||||
|
description: >
|
||||||
|
Migrate Chakra UI projects from v2 to v3, covering package changes, codemods,
|
||||||
|
provider setup, color mode, prop renaming, compound components, theming,
|
||||||
|
recipes, and Next.js updates. Use this skill whenever a user is upgrading
|
||||||
|
Chakra UI versions, encountering breaking changes after an upgrade, converting
|
||||||
|
old v2 patterns (ColorModeScript, useColorModeValue, styleConfig, extendTheme,
|
||||||
|
isDisabled, colorScheme, @chakra-ui/icons, framer-motion dependency), fixing
|
||||||
|
compound component patterns, or asking about differences between Chakra UI v2
|
||||||
|
and v3 — even if they don't say "migrate" or "upgrade" explicitly.
|
||||||
|
---
|
||||||
|
|
||||||
|
# Chakra UI Migration: v2 → v3
|
||||||
|
|
||||||
|
You are guiding a developer through migrating their project from Chakra UI v2 to
|
||||||
|
v3. Work through the steps below in order. Inspect the project first — never
|
||||||
|
guess the package versions or framework.
|
||||||
|
|
||||||
|
> **Node requirement:** Chakra UI v3 requires Node >= 20.x. Confirm before
|
||||||
|
> proceeding if the environment is uncertain.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 1 — Inspect the project
|
||||||
|
|
||||||
|
Read these files to understand the current state:
|
||||||
|
|
||||||
|
```
|
||||||
|
package.json
|
||||||
|
```
|
||||||
|
|
||||||
|
Look for:
|
||||||
|
|
||||||
|
- Current `@chakra-ui/react` version (v2.x vs v3.x)
|
||||||
|
- Related packages: `@chakra-ui/icons`, `@chakra-ui/hooks`,
|
||||||
|
`@chakra-ui/next-js`, `@emotion/styled`, `framer-motion`
|
||||||
|
- Framework: Next.js (App Router or Pages Router), Vite, plain React
|
||||||
|
- Package manager (from lockfiles: `pnpm-lock.yaml`, `yarn.lock`, `bun.lock`,
|
||||||
|
`package-lock.json`)
|
||||||
|
|
||||||
|
Also spot-check key files when helpful:
|
||||||
|
|
||||||
|
- Provider / theme setup (`_app.tsx`, `layout.tsx`, `theme.ts`)
|
||||||
|
- Color mode usage (`ColorModeScript`, `useColorMode`, `useColorModeValue`)
|
||||||
|
- Any component files showing heavy v2 patterns
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 2 — Update packages
|
||||||
|
|
||||||
|
### Remove v2-only dependencies
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# npm
|
||||||
|
npm uninstall @chakra-ui/icons @chakra-ui/hooks @chakra-ui/next-js @emotion/styled framer-motion
|
||||||
|
|
||||||
|
# pnpm
|
||||||
|
pnpm remove @chakra-ui/icons @chakra-ui/hooks @chakra-ui/next-js @emotion/styled framer-motion
|
||||||
|
|
||||||
|
# yarn
|
||||||
|
yarn remove @chakra-ui/icons @chakra-ui/hooks @chakra-ui/next-js @emotion/styled framer-motion
|
||||||
|
```
|
||||||
|
|
||||||
|
`@emotion/styled` and `framer-motion` are no longer required in v3.
|
||||||
|
|
||||||
|
### Install v3 core packages
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# npm
|
||||||
|
npm install @chakra-ui/react @emotion/react
|
||||||
|
|
||||||
|
# pnpm
|
||||||
|
pnpm add @chakra-ui/react @emotion/react
|
||||||
|
|
||||||
|
# yarn
|
||||||
|
yarn add @chakra-ui/react @emotion/react
|
||||||
|
```
|
||||||
|
|
||||||
|
### Replacements for removed packages
|
||||||
|
|
||||||
|
| Removed | Replacement |
|
||||||
|
| -------------------- | -------------------------------------------- |
|
||||||
|
| `@chakra-ui/icons` | `lucide-react` or `react-icons` |
|
||||||
|
| `@chakra-ui/hooks` | `react-use` or `usehooks-ts` |
|
||||||
|
| `@chakra-ui/next-js` | `asChild` prop pattern (see Next.js section) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 3 — Run the codemod
|
||||||
|
|
||||||
|
The official codemod handles most mechanical changes: component renames, prop
|
||||||
|
updates, import rewrites, and compound component restructuring. It does not
|
||||||
|
replace manual review — plan to audit the output.
|
||||||
|
|
||||||
|
**Dry run first (no files changed):**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx @chakra-ui/codemod upgrade --dry
|
||||||
|
```
|
||||||
|
|
||||||
|
Review what it proposes. When satisfied:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx @chakra-ui/codemod upgrade
|
||||||
|
```
|
||||||
|
|
||||||
|
After the codemod, commit the changes before making manual edits so you have a
|
||||||
|
clean diff to work from.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 4 — Update the Provider
|
||||||
|
|
||||||
|
### Old v2 pattern
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// v2
|
||||||
|
import { ChakraProvider } from "@chakra-ui/react"
|
||||||
|
import theme from "./theme"
|
||||||
|
|
||||||
|
;<ChakraProvider theme={theme}>{children}</ChakraProvider>
|
||||||
|
```
|
||||||
|
|
||||||
|
### New v3 pattern (using Chakra CLI snippets)
|
||||||
|
|
||||||
|
Generate the provider and component snippets:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx @chakra-ui/cli snippet add
|
||||||
|
```
|
||||||
|
|
||||||
|
This creates `components/ui/provider.tsx` (plus `toaster` and `tooltip`
|
||||||
|
snippets) and automatically installs required npm dependencies — including
|
||||||
|
`next-themes`. Import and use it:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// v3 — app/layout.tsx (Next.js App Router)
|
||||||
|
import { Provider } from "@/components/ui/provider"
|
||||||
|
|
||||||
|
;<html lang="en" suppressHydrationWarning>
|
||||||
|
<body>
|
||||||
|
<Provider>{children}</Provider>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
```
|
||||||
|
|
||||||
|
The `Provider` file includes `"use client"` — do not add it to `layout.tsx`. See
|
||||||
|
the Next.js section for Pages Router placement.
|
||||||
|
|
||||||
|
### Custom theme in v3
|
||||||
|
|
||||||
|
Replace `extendTheme` with `createSystem`:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// v2
|
||||||
|
import { extendTheme } from "@chakra-ui/react"
|
||||||
|
// v3
|
||||||
|
import { createSystem, defaultConfig, defineConfig } from "@chakra-ui/react"
|
||||||
|
|
||||||
|
export const theme = extendTheme({ colors: { brand: { 500: "#2196f3" } } })
|
||||||
|
|
||||||
|
const config = defineConfig({
|
||||||
|
theme: { tokens: { colors: { brand: { 500: { value: "#2196f3" } } } } },
|
||||||
|
})
|
||||||
|
export const system = createSystem(defaultConfig, config)
|
||||||
|
```
|
||||||
|
|
||||||
|
Pass `system` to `ChakraProvider` via `value={system}`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 5 — Color mode migration
|
||||||
|
|
||||||
|
### Remove all v2 color mode patterns
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// REMOVE these v2 imports and usages:
|
||||||
|
import { ColorModeScript } from "@chakra-ui/react"
|
||||||
|
// ❌
|
||||||
|
import { useColorMode } from "@chakra-ui/react"
|
||||||
|
// ❌ (use next-themes)
|
||||||
|
import { useColorModeValue } from "@chakra-ui/react"
|
||||||
|
// ❌ (use CSS tokens)
|
||||||
|
import { DarkMode, LightMode } from "@chakra-ui/react"
|
||||||
|
|
||||||
|
// ❌
|
||||||
|
|
||||||
|
// Also remove from _document.tsx:
|
||||||
|
;<ColorModeScript initialColorMode={theme.config.initialColorMode} /> // ❌
|
||||||
|
```
|
||||||
|
|
||||||
|
### v3 color mode approach
|
||||||
|
|
||||||
|
Color mode is handled by `next-themes` via the generated `Provider`. Use
|
||||||
|
semantic tokens that automatically respond to the active color mode:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Use Chakra semantic tokens — they flip automatically in dark mode
|
||||||
|
<Box color="fg.default" bg="bg.subtle">
|
||||||
|
...
|
||||||
|
</Box>
|
||||||
|
```
|
||||||
|
|
||||||
|
For a color mode toggle, use the generated `components/ui/color-mode.tsx`
|
||||||
|
snippet or `useColorMode` from `next-themes` directly.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 6 — Prop renames
|
||||||
|
|
||||||
|
These boolean and style props were renamed in v3 for consistency with HTML and
|
||||||
|
modern React conventions. The codemod catches most of these, but verify manually
|
||||||
|
afterward.
|
||||||
|
|
||||||
|
### Boolean props
|
||||||
|
|
||||||
|
| v2 | v3 |
|
||||||
|
| ----------------- | --------------- |
|
||||||
|
| `isOpen` | `open` |
|
||||||
|
| `defaultIsOpen` | `defaultOpen` |
|
||||||
|
| `isDisabled` | `disabled` |
|
||||||
|
| `isInvalid` | `invalid` |
|
||||||
|
| `isRequired` | `required` |
|
||||||
|
| `isReadOnly` | `readOnly` |
|
||||||
|
| `isChecked` | `checked` |
|
||||||
|
| `isLoaded` | `loaded` |
|
||||||
|
| `isIndeterminate` | `indeterminate` |
|
||||||
|
|
||||||
|
### Style and layout props
|
||||||
|
|
||||||
|
| v2 | v3 |
|
||||||
|
| ----------------- | --------------------------- |
|
||||||
|
| `colorScheme` | `colorPalette` |
|
||||||
|
| `noOfLines` | `lineClamp` |
|
||||||
|
| `truncated` | `truncate` |
|
||||||
|
| `spacing` (Stack) | `gap` |
|
||||||
|
| `apply` | `textStyle` or `layerStyle` |
|
||||||
|
|
||||||
|
### Nested style props
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// v2 — sx with nested pseudo-selectors
|
||||||
|
<Box sx={{ "&:hover": { color: "blue.500" } }} />
|
||||||
|
|
||||||
|
// v3 — css prop with "&" selectors
|
||||||
|
<Box css={{ "&:hover": { color: "blue.500" } }} />
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 7 — Component migrations
|
||||||
|
|
||||||
|
### Renamed components
|
||||||
|
|
||||||
|
| v2 | v3 |
|
||||||
|
| ------------- | ----------------------------------- |
|
||||||
|
| `Modal` | `Dialog` |
|
||||||
|
| `FormControl` | `Field` |
|
||||||
|
| `Select` | `NativeSelect` |
|
||||||
|
| `AlertDialog` | `AlertDialog` (compound, see below) |
|
||||||
|
|
||||||
|
`Modal` is the most common rename — every `<Modal>`, `<ModalOverlay>`,
|
||||||
|
`<ModalContent>`, `<ModalHeader>`, `<ModalBody>`, `<ModalFooter>`, and
|
||||||
|
`<ModalCloseButton>` becomes a `Dialog.*` compound part:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// v2
|
||||||
|
<Modal isOpen={open} onClose={onClose}>
|
||||||
|
<ModalOverlay />
|
||||||
|
<ModalContent>
|
||||||
|
<ModalHeader>Title</ModalHeader>
|
||||||
|
<ModalBody>Body</ModalBody>
|
||||||
|
<ModalFooter><Button onClick={onClose}>Close</Button></ModalFooter>
|
||||||
|
</ModalContent>
|
||||||
|
</Modal>
|
||||||
|
|
||||||
|
// v3
|
||||||
|
<Dialog.Root open={open} onOpenChange={({ open }) => setOpen(open)}>
|
||||||
|
<Dialog.Backdrop />
|
||||||
|
<Dialog.Positioner>
|
||||||
|
<Dialog.Content>
|
||||||
|
<Dialog.Header><Dialog.Title>Title</Dialog.Title></Dialog.Header>
|
||||||
|
<Dialog.Body>Body</Dialog.Body>
|
||||||
|
<Dialog.Footer><Button onClick={() => setOpen(false)}>Close</Button></Dialog.Footer>
|
||||||
|
<Dialog.CloseTrigger />
|
||||||
|
</Dialog.Content>
|
||||||
|
</Dialog.Positioner>
|
||||||
|
</Dialog.Root>
|
||||||
|
```
|
||||||
|
|
||||||
|
### Compound component rewrites
|
||||||
|
|
||||||
|
v3 adopts a consistent compound component API. The codemod handles many of
|
||||||
|
these, but complex custom usage needs manual review.
|
||||||
|
|
||||||
|
**Checkbox**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// v2
|
||||||
|
<Checkbox isChecked={val} onChange={fn}>Label</Checkbox>
|
||||||
|
|
||||||
|
// v3
|
||||||
|
<Checkbox.Root checked={val} onCheckedChange={fn}>
|
||||||
|
<Checkbox.Control><Checkbox.Indicator /></Checkbox.Control>
|
||||||
|
<Checkbox.Label>Label</Checkbox.Label>
|
||||||
|
</Checkbox.Root>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Progress**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// v2
|
||||||
|
<Progress value={60} colorScheme="blue" />
|
||||||
|
|
||||||
|
// v3
|
||||||
|
<Progress.Root value={60} colorPalette="blue">
|
||||||
|
<Progress.Track><Progress.Range /></Progress.Track>
|
||||||
|
</Progress.Root>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Accordion**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// v2
|
||||||
|
<Accordion><AccordionItem><AccordionButton /><AccordionPanel /></AccordionItem></Accordion>
|
||||||
|
|
||||||
|
// v3
|
||||||
|
<Accordion.Root>
|
||||||
|
<Accordion.Item value="item-1">
|
||||||
|
<Accordion.ItemTrigger />
|
||||||
|
<Accordion.ItemContent />
|
||||||
|
</Accordion.Item>
|
||||||
|
</Accordion.Root>
|
||||||
|
```
|
||||||
|
|
||||||
|
**FormControl → Field**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// v2
|
||||||
|
<FormControl isInvalid={!!error} isRequired>
|
||||||
|
<FormLabel>Email</FormLabel>
|
||||||
|
<Input type="email" />
|
||||||
|
<FormErrorMessage>{error}</FormErrorMessage>
|
||||||
|
<FormHelperText>We'll never share your email.</FormHelperText>
|
||||||
|
</FormControl>
|
||||||
|
|
||||||
|
// v3
|
||||||
|
<Field.Root invalid={!!error} required>
|
||||||
|
<Field.Label>Email</Field.Label>
|
||||||
|
<Input type="email" />
|
||||||
|
<Field.ErrorText>{error}</Field.ErrorText>
|
||||||
|
<Field.HelpText>We'll never share your email.</Field.HelpText>
|
||||||
|
</Field.Root>
|
||||||
|
```
|
||||||
|
|
||||||
|
All `FormControl` sub-parts map to `Field.*`:
|
||||||
|
|
||||||
|
- `FormLabel` → `Field.Label`
|
||||||
|
- `FormErrorMessage` → `Field.ErrorText`
|
||||||
|
- `FormHelperText` → `Field.HelpText`
|
||||||
|
- `FormControl` props `isInvalid`, `isRequired`, `isDisabled` → `invalid`,
|
||||||
|
`required`, `disabled`
|
||||||
|
|
||||||
|
**Dialog / Drawer / Menu / Tabs** follow the same compound pattern: use
|
||||||
|
`ComponentName.Root`, `.Trigger`, `.Content`, `.Item`, etc. Check the Chakra UI
|
||||||
|
v3 docs for the specific compound API for each.
|
||||||
|
|
||||||
|
### Next.js Image and Link (replacing @chakra-ui/next-js)
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// v2 — @chakra-ui/next-js
|
||||||
|
import { LinkOverlay } from "@chakra-ui/next-js"
|
||||||
|
|
||||||
|
// v3 — asChild pattern
|
||||||
|
import NextLink from "next/link"
|
||||||
|
<ChakraLink asChild><NextLink href="/about">About</NextLink></ChakraLink>
|
||||||
|
|
||||||
|
import NextImage from "next/image"
|
||||||
|
<ChakraImage asChild><NextImage src="..." alt="..." /></ChakraImage>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 8 — Theming migration
|
||||||
|
|
||||||
|
### styleConfig and multiStyleConfig → recipes
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// v3 — single component (recipe)
|
||||||
|
import { defineRecipe } from "@chakra-ui/react"
|
||||||
|
|
||||||
|
// v2
|
||||||
|
const buttonStyle = {
|
||||||
|
baseStyle: { fontWeight: "bold" },
|
||||||
|
variants: { solid: { bg: "blue.500" } },
|
||||||
|
defaultProps: { variant: "solid" },
|
||||||
|
}
|
||||||
|
|
||||||
|
const buttonRecipe = defineRecipe({
|
||||||
|
base: { fontWeight: "bold" },
|
||||||
|
variants: { variant: { solid: { bg: "blue.500" } } },
|
||||||
|
defaultVariants: { variant: "solid" },
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// v3 — slot recipe
|
||||||
|
import { defineSlotRecipe } from "@chakra-ui/react"
|
||||||
|
|
||||||
|
// v2 — multiStyleConfig (multi-part component)
|
||||||
|
const cardStyle = multiStyleConfig({
|
||||||
|
parts: ["root", "header"],
|
||||||
|
baseStyle: { root: { bg: "white" }, header: { fontWeight: "bold" } },
|
||||||
|
})
|
||||||
|
|
||||||
|
const cardSlotRecipe = defineSlotRecipe({
|
||||||
|
slots: ["root", "header"],
|
||||||
|
base: { root: { bg: "white" }, header: { fontWeight: "bold" } },
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
### Typegen for custom tokens
|
||||||
|
|
||||||
|
After adding custom tokens, semantic tokens, recipes, or slot recipes, run
|
||||||
|
typegen to keep TypeScript types in sync:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx @chakra-ui/cli typegen ./theme.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
> **Complex theme migrations** — if you're moving a large v2 theme with many
|
||||||
|
> custom tokens, semantic tokens, or multi-part component styles, use the
|
||||||
|
> `chakra-ui-theming` skill. It covers the full token/recipe/slot-recipe API in
|
||||||
|
> depth and is a better guide than this section alone.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 9 — Next.js specifics
|
||||||
|
|
||||||
|
### App Router
|
||||||
|
|
||||||
|
- Place `<Provider>` in `app/layout.tsx` (Server Component — no `"use client"`)
|
||||||
|
- The generated `components/ui/provider.tsx` already has `"use client"`
|
||||||
|
- Add `suppressHydrationWarning` to `<html>` to prevent color mode flicker
|
||||||
|
- Do not wrap the entire app or layout in `"use client"`
|
||||||
|
|
||||||
|
### Pages Router
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// pages/_app.js
|
||||||
|
import { Provider } from "@/components/ui/provider"
|
||||||
|
|
||||||
|
export default function App({ Component, pageProps }) {
|
||||||
|
return (
|
||||||
|
<Provider>
|
||||||
|
<Component {...pageProps} />
|
||||||
|
</Provider>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Remove any `ColorModeScript` from `pages/_document.tsx` — it is not used in v3.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 10 — Validation checklist
|
||||||
|
|
||||||
|
Work through this after the migration is complete:
|
||||||
|
|
||||||
|
- [ ] Reinstall dependencies: `npm install` / `pnpm install`
|
||||||
|
- [ ] TypeScript: `npx tsc --noEmit` — resolve all type errors
|
||||||
|
- [ ] Lint: `npm run lint`
|
||||||
|
- [ ] Build: `npm run build`
|
||||||
|
- [ ] Visually verify color mode toggle (light ↔ dark)
|
||||||
|
- [ ] Test interactive components: Dialog, Drawer, Menu, Tabs, Accordion
|
||||||
|
- [ ] Test form components: Checkbox, Select/NativeSelect, Input, Radio
|
||||||
|
- [ ] Check for visual regressions across key pages
|
||||||
|
- [ ] Search codebase for leftover v2 imports:
|
||||||
|
```bash
|
||||||
|
grep -r "ColorModeScript\|useColorModeValue\|extendTheme\|styleConfig\|@chakra-ui/icons\|@chakra-ui/next-js" src/
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Clarifying questions (when context is unclear)
|
||||||
|
|
||||||
|
If the user's version, framework, or scope is ambiguous, ask:
|
||||||
|
|
||||||
|
1. "What version of `@chakra-ui/react` are you on right now?"
|
||||||
|
2. "Are you using Next.js App Router, Pages Router, Vite, or plain React?"
|
||||||
|
3. "Are you migrating the full codebase or just specific components?"
|
||||||
|
|
||||||
|
State assumptions clearly if you proceed without asking.
|
||||||
@@ -0,0 +1,284 @@
|
|||||||
|
---
|
||||||
|
name: chakra-ui-refactor
|
||||||
|
description: >
|
||||||
|
Review, convert, and improve UI code using Chakra UI v3. Use this skill
|
||||||
|
whenever a user wants to review Chakra UI code for issues, convert plain
|
||||||
|
HTML/CSS, Tailwind, CSS Modules, or styled-components to Chakra UI, clean up
|
||||||
|
messy Chakra components, fix layout structure or token usage, or asks anything
|
||||||
|
like "is this correct", "what's wrong with this", "review my component",
|
||||||
|
"refactor this", "clean up", "convert", or "chakra-ify this" — even without
|
||||||
|
the words "review" or "refactor". Trigger on any request to check, improve, or
|
||||||
|
convert Chakra UI code, however casually phrased.
|
||||||
|
---
|
||||||
|
|
||||||
|
# Chakra UI Refactor & Review
|
||||||
|
|
||||||
|
You are reviewing and improving UI code using Chakra UI v3. Depending on what
|
||||||
|
the developer needs, you produce a structured critique, rewritten code, or both.
|
||||||
|
Read the code and project context fully before producing any output.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 1 — Orient and determine intent
|
||||||
|
|
||||||
|
Before any output, establish:
|
||||||
|
|
||||||
|
- **Chakra UI version** — check `package.json`; use v3 by default
|
||||||
|
- **Framework** — Next.js App Router, Pages Router, Vite, plain React
|
||||||
|
- **Source type** — existing Chakra, plain HTML/CSS, Tailwind, CSS Modules,
|
||||||
|
styled-components
|
||||||
|
- **What the user is asking:**
|
||||||
|
- **Review only** — "check this", "is this correct/idiomatic", "what's wrong",
|
||||||
|
"review my code" → produce a critique with targeted fixes, no full rewrite
|
||||||
|
- **Refactor / convert** — "refactor this", "convert from Tailwind", "clean
|
||||||
|
this up" → produce rewritten code
|
||||||
|
- **Both** — "review and fix" → critique first, then the rewritten code
|
||||||
|
|
||||||
|
State your reading at the top of the response (e.g. "Reviewing as existing
|
||||||
|
Chakra v3 code. Assuming Next.js App Router.").
|
||||||
|
|
||||||
|
If code isn't shared yet, ask for it. Don't review a description of code.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 2 — Analyze the code
|
||||||
|
|
||||||
|
Work through the code across these dimensions regardless of output mode. For
|
||||||
|
review, they become findings. For refactor, they become the checklist of what to
|
||||||
|
fix.
|
||||||
|
|
||||||
|
**Accessibility**
|
||||||
|
|
||||||
|
- Do all interactive elements have accessible labels? (`aria-label` on icon
|
||||||
|
buttons, `htmlFor`/`id` on label+input pairs, `alt` on images)
|
||||||
|
- Is keyboard navigation possible? (focus rings not suppressed, interactive
|
||||||
|
elements are actually focusable)
|
||||||
|
- Does the heading hierarchy make sense? (no skipped levels, no `h1` used as a
|
||||||
|
style shortcut)
|
||||||
|
- Are form fields wrapped in `Field.Root` with `Field.Label` and
|
||||||
|
`Field.ErrorText`?
|
||||||
|
- Does the component work without color as the only signal?
|
||||||
|
|
||||||
|
**Responsiveness**
|
||||||
|
|
||||||
|
- Do layout components specify behavior at multiple breakpoints?
|
||||||
|
- Are there hardcoded pixel values where responsive tokens would work better?
|
||||||
|
- Would this break on mobile? (fixed widths, `overflow: hidden` on small
|
||||||
|
viewports)
|
||||||
|
|
||||||
|
**Chakra API correctness**
|
||||||
|
|
||||||
|
- Are v3 prop names used? (`disabled` not `isDisabled`, `colorPalette` not
|
||||||
|
`colorScheme`, `gap` not `spacing`, `open` not `isOpen`)
|
||||||
|
- Are compound components used correctly? (`Field.Root`/`Field.Label`,
|
||||||
|
`Dialog.Root`/`Dialog.Content`, etc.)
|
||||||
|
- Is `"use client"` placed correctly in Next.js App Router?
|
||||||
|
- Are there v2 patterns still present? (`extendTheme`, `ColorModeScript`,
|
||||||
|
`useColorModeValue`, `sx` prop)
|
||||||
|
|
||||||
|
**Token and style usage**
|
||||||
|
|
||||||
|
- Are hardcoded colors used where semantic tokens would work? (`bg="#f9fafb"` →
|
||||||
|
`bg="bg.subtle"`)
|
||||||
|
- Are raw hex or palette values used instead of semantic tokens? These won't
|
||||||
|
respect dark mode.
|
||||||
|
- Are there inline `style={{}}` props that should be Chakra style props?
|
||||||
|
|
||||||
|
**Component structure**
|
||||||
|
|
||||||
|
- Is there unnecessary nesting? (`Box > Box > Box` when one would do)
|
||||||
|
- Is manual spacing (`mt={4}` on every child) used where `Stack gap={4}` would
|
||||||
|
be cleaner?
|
||||||
|
- Are the right layout primitives used? (`Flex` vs `Stack` vs `Grid` vs
|
||||||
|
`SimpleGrid`)
|
||||||
|
|
||||||
|
**Maintainability**
|
||||||
|
|
||||||
|
- Does the same visual pattern repeat 3+ times? (candidate for a component or
|
||||||
|
recipe)
|
||||||
|
- Are there one-off style overrides that suggest a recipe or slot recipe?
|
||||||
|
- Are prop types / TypeScript types present and accurate?
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 3a — Review output
|
||||||
|
|
||||||
|
Use this when the user wants a critique, not a rewrite.
|
||||||
|
|
||||||
|
Categorize findings by impact:
|
||||||
|
|
||||||
|
**Critical** — bugs and accessibility failures that break behavior or exclude
|
||||||
|
users
|
||||||
|
|
||||||
|
- Missing `aria-label` on an icon-only button
|
||||||
|
- Form field with no label association
|
||||||
|
- Interactive `Box` with `onClick` but no keyboard access
|
||||||
|
- Wrong v3 prop name that silently does nothing (`isDisabled` doesn't disable in
|
||||||
|
v3)
|
||||||
|
- `"use client"` missing on a component that uses hooks in App Router
|
||||||
|
|
||||||
|
**Improvements** — correctness and quality issues that aren't urgent
|
||||||
|
|
||||||
|
- Hardcoded colors that break dark mode
|
||||||
|
- Missing responsive breakpoints
|
||||||
|
- Unnecessary nesting or wrong layout primitive
|
||||||
|
- v2 patterns that still work but should be updated
|
||||||
|
|
||||||
|
**Optional suggestions** — non-blocking ideas
|
||||||
|
|
||||||
|
- Extract a repeated pattern into a component
|
||||||
|
- Replace a one-off style with a recipe variant
|
||||||
|
- Add a missing TypeScript type
|
||||||
|
|
||||||
|
For each critical issue and significant improvement, show a minimal fix:
|
||||||
|
|
||||||
|
```
|
||||||
|
**Missing aria-label on close button** (Critical)
|
||||||
|
The IconButton for closing the dialog has no accessible label.
|
||||||
|
|
||||||
|
// Before
|
||||||
|
<IconButton icon={<CloseIcon />} onClick={onClose} />
|
||||||
|
// After
|
||||||
|
<IconButton aria-label="Close dialog" icon={<CloseIcon />} onClick={onClose} />
|
||||||
|
```
|
||||||
|
|
||||||
|
Skip sections with nothing to report. Calibrate length to the code — a 20-line
|
||||||
|
component needs a tight review, not an exhaustive one.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 3b — Refactor / convert output
|
||||||
|
|
||||||
|
Use this when the user wants rewritten code.
|
||||||
|
|
||||||
|
### Conversion strategy by source
|
||||||
|
|
||||||
|
**From plain HTML / CSS**
|
||||||
|
|
||||||
|
| HTML | Chakra equivalent |
|
||||||
|
| ------------------------ | ------------------------------------------- |
|
||||||
|
| `<div>` layout wrapper | `Box`, `Flex`, `Stack`, `Grid` |
|
||||||
|
| `<section>`, `<article>` | `Box as="section"`, `Box as="article"` |
|
||||||
|
| `<nav>` | `Box as="nav"` |
|
||||||
|
| `<ul>` / `<li>` | `Box as="ul"` / `Box as="li"`, or `Stack` |
|
||||||
|
| `<button>` | `Button` or `IconButton` |
|
||||||
|
| `<a>` | `Link` |
|
||||||
|
| `<img>` | `Image` (preserve `alt`) |
|
||||||
|
| `<input>`, `<select>` | `Input`, `NativeSelect` inside `Field.Root` |
|
||||||
|
|
||||||
|
| CSS | Chakra style prop |
|
||||||
|
| ------------------------ | ----------------------------- |
|
||||||
|
| `display: flex` | `Flex` or `display="flex"` |
|
||||||
|
| `flex-direction: column` | `Stack` or `flexDir="column"` |
|
||||||
|
| `gap: 16px` | `gap={4}` (1 unit = 4px) |
|
||||||
|
| `padding: 16px 24px` | `py={4} px={6}` |
|
||||||
|
| `border-radius: 8px` | `rounded="md"` |
|
||||||
|
| `color: #6b7280` | `color="fg.muted"` |
|
||||||
|
| `background: #f9fafb` | `bg="bg.subtle"` |
|
||||||
|
|
||||||
|
**From Tailwind CSS**
|
||||||
|
|
||||||
|
| Tailwind | Chakra |
|
||||||
|
| ------------------------------ | ---------------------------------------- |
|
||||||
|
| `flex`, `flex-col`, `flex-row` | `Flex`, `flexDir` |
|
||||||
|
| `gap-4` | `gap={4}` |
|
||||||
|
| `p-4`, `px-6`, `py-2` | `p={4}`, `px={6}`, `py={2}` |
|
||||||
|
| `text-sm`, `font-bold` | `fontSize="sm"`, `fontWeight="bold"` |
|
||||||
|
| `rounded-lg`, `shadow-md` | `rounded="lg"`, `shadow="md"` |
|
||||||
|
| `w-full`, `max-w-lg` | `w="full"`, `maxW="lg"` |
|
||||||
|
| `hidden md:flex` | `display={{ base: "none", md: "flex" }}` |
|
||||||
|
| `grid grid-cols-3` | `SimpleGrid columns={3}` |
|
||||||
|
| `text-gray-500`, `bg-gray-100` | `color="fg.muted"`, `bg="bg.subtle"` |
|
||||||
|
| `hover:bg-gray-100` | `_hover={{ bg: "bg.subtle" }}` |
|
||||||
|
|
||||||
|
Replace Tailwind responsive prefixes with Chakra's breakpoint object syntax:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Tailwind: text-sm md:base lg:text-lg
|
||||||
|
<Text fontSize={{ base: "sm", md: "md", lg: "lg" }} />
|
||||||
|
```
|
||||||
|
|
||||||
|
**From CSS Modules** — convert what you can to Chakra props; keep `className`
|
||||||
|
for styles that can't be expressed as props (animations, complex selectors):
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Before
|
||||||
|
<div className={styles.card}>...</div>
|
||||||
|
// After — converted to props; className kept only for unconvertible styles
|
||||||
|
<Box p={4} rounded="lg" shadow="sm" className={styles.fadeIn}>...</Box>
|
||||||
|
```
|
||||||
|
|
||||||
|
Once all class names are eliminated, remove the import entirely.
|
||||||
|
|
||||||
|
**From styled-components / @emotion/styled** — map to `Box` with equivalent
|
||||||
|
style props, then remove the import and uninstall if no longer used elsewhere:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Before
|
||||||
|
const Card = styled.div`padding: 1rem; &:hover { background: #f3f4f6; }`
|
||||||
|
// After
|
||||||
|
<Box p={4} _hover={{ bg: "bg.muted" }} />
|
||||||
|
```
|
||||||
|
|
||||||
|
**From existing Chakra UI (cleanup)**
|
||||||
|
|
||||||
|
- Flatten `Box > Box > Box` nesting; replace `mt`/`mb` on every child with
|
||||||
|
`Stack gap={N}`
|
||||||
|
- Replace `sx` with `css` (v3 rename); update nested `&:hover` selectors inside
|
||||||
|
it
|
||||||
|
- Replace `bg="gray.50"` → `bg="bg.subtle"` and other semantic token equivalents
|
||||||
|
- Update v2 prop names: `isDisabled→disabled`, `colorScheme→colorPalette`,
|
||||||
|
`spacing→gap`
|
||||||
|
- Update compound components: `FormControl→Field.Root`, `Modal→Dialog`,
|
||||||
|
`Select→NativeSelect`
|
||||||
|
|
||||||
|
### Preserve behavior — non-negotiable
|
||||||
|
|
||||||
|
- Keep all event handlers, state variables, and conditional rendering exactly
|
||||||
|
as-is
|
||||||
|
- Keep `aria-*` attributes; add missing ones where clearly needed
|
||||||
|
- Keep semantic HTML intent (`<nav>` → `Box as="nav"`, not just `Box`)
|
||||||
|
- Keep `"use client"` where it exists; add it only when the component genuinely
|
||||||
|
needs it
|
||||||
|
- Don't add `"use client"` just because a component uses Chakra UI
|
||||||
|
- A partially-converted component that works is better than a fully-converted
|
||||||
|
one that doesn't
|
||||||
|
|
||||||
|
### `asChild` for Next.js Link and Image
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import NextLink from "next/link"
|
||||||
|
<ChakraLink asChild><NextLink href="/about">About</NextLink></ChakraLink>
|
||||||
|
|
||||||
|
import NextImage from "next/image"
|
||||||
|
<ChakraImage asChild><NextImage src="/hero.png" alt="Hero" width={800} height={400} /></ChakraImage>
|
||||||
|
```
|
||||||
|
|
||||||
|
### Refactor output format
|
||||||
|
|
||||||
|
**1. Refactored code** — complete, runnable, with correct imports
|
||||||
|
|
||||||
|
**2. What changed** — concise list focused on non-obvious decisions:
|
||||||
|
|
||||||
|
```
|
||||||
|
- Replaced <div className="flex gap-4"> with <Flex gap={4}>
|
||||||
|
- Replaced bg="#f9fafb" with bg="bg.subtle" for dark mode compatibility
|
||||||
|
- Kept form submit handler and validation logic unchanged
|
||||||
|
- Added aria-label to close icon button (was missing)
|
||||||
|
```
|
||||||
|
|
||||||
|
**3. Suggestions** (optional) — meaningful improvements beyond this refactor:
|
||||||
|
extracting a reusable component, adopting a recipe, migrating a v2 pattern.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## When to ask vs proceed
|
||||||
|
|
||||||
|
Proceed if the code and intent are clear. Ask when:
|
||||||
|
|
||||||
|
- The code isn't shared yet
|
||||||
|
- The component is very large and scope is unclear
|
||||||
|
- There's context or state you can't see that would change the review
|
||||||
|
- There's ambiguous behavior that could be interpreted multiple ways
|
||||||
|
|
||||||
|
State assumptions at the top of the response when you proceed without asking.
|
||||||
@@ -0,0 +1,374 @@
|
|||||||
|
---
|
||||||
|
name: chakra-ui-builder
|
||||||
|
description: >
|
||||||
|
Build responsive, accessible UI components and layouts using Chakra UI v3,
|
||||||
|
install or configure Chakra UI in new and existing projects, and design
|
||||||
|
scalable themes using tokens, semantic tokens, recipes, and slot recipes. Use
|
||||||
|
this skill whenever a user asks to build, create, or generate any UI
|
||||||
|
component, page, form, dashboard, navbar, card, landing section, pricing
|
||||||
|
table, or layout using Chakra UI; wants to add Chakra UI to a project, set up
|
||||||
|
ChakraProvider, run CLI snippets, configure color mode, or fix provider
|
||||||
|
wrapping; or asks about theming — defining brand colors, design tokens,
|
||||||
|
semantic tokens, dark mode values, component recipes, slot recipes, typegen,
|
||||||
|
or ejecting the default theme. Trigger on any Chakra UI building, setup, or
|
||||||
|
theming or charts request, however casually phrased — "add my brand colors",
|
||||||
|
"make a reusable card style", "build a bar chart", "show me a line chart",
|
||||||
|
"make me a login form", "build a sidebar", "add Chakra to my app".
|
||||||
|
---
|
||||||
|
|
||||||
|
# Chakra UI Builder
|
||||||
|
|
||||||
|
You are building UI with Chakra UI v3 and helping developers set up Chakra UI in
|
||||||
|
their projects. Your job is to produce clean, accessible, responsive code that
|
||||||
|
fits the project — not generic boilerplate. Read the project context first, then
|
||||||
|
build or set up.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 1 — Read the project context
|
||||||
|
|
||||||
|
Check `package.json` if available. Look for:
|
||||||
|
|
||||||
|
- Chakra UI version (use v3 patterns by default; only use v2 if explicitly on
|
||||||
|
v2)
|
||||||
|
- Framework: Next.js App Router, Pages Router, Vite, plain React
|
||||||
|
- TypeScript or JavaScript
|
||||||
|
- Package manager (from lockfile: `pnpm-lock.yaml`, `yarn.lock`, `bun.lock`,
|
||||||
|
`package-lock.json`)
|
||||||
|
|
||||||
|
Also glance at existing components if the user references them, so your code
|
||||||
|
matches the conventions already in use (naming, file structure, import style).
|
||||||
|
|
||||||
|
If the requirements are vague or the component is complex enough that choices
|
||||||
|
matter (layout direction, data shape, color palette, number of variants), ask
|
||||||
|
before building rather than generating something that needs to be thrown away.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Project setup
|
||||||
|
|
||||||
|
If Chakra UI isn't installed yet, complete setup before building.
|
||||||
|
|
||||||
|
### Install
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# npm
|
||||||
|
npm install @chakra-ui/react @emotion/react
|
||||||
|
|
||||||
|
# pnpm
|
||||||
|
pnpm add @chakra-ui/react @emotion/react
|
||||||
|
|
||||||
|
# yarn
|
||||||
|
yarn add @chakra-ui/react @emotion/react
|
||||||
|
|
||||||
|
# bun
|
||||||
|
bun add @chakra-ui/react @emotion/react
|
||||||
|
```
|
||||||
|
|
||||||
|
### Generate snippets with the CLI
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx @chakra-ui/cli snippet add
|
||||||
|
```
|
||||||
|
|
||||||
|
With no arguments this adds the recommended set — `provider`, `toaster`, and
|
||||||
|
`tooltip` — and automatically installs required dependencies (including
|
||||||
|
`next-themes`). Use `--all` to add every snippet, or `snippet list` to browse
|
||||||
|
first.
|
||||||
|
|
||||||
|
The CLI detects your framework and writes files to the right place:
|
||||||
|
|
||||||
|
| Framework | Output path |
|
||||||
|
| --------------------- | -------------------- |
|
||||||
|
| Next.js (with `src/`) | `src/components/ui/` |
|
||||||
|
| Next.js (no `src/`) | `components/ui/` |
|
||||||
|
| Vite / plain React | `src/components/ui/` |
|
||||||
|
| Remix | `app/components/ui/` |
|
||||||
|
|
||||||
|
### Wire up the Provider
|
||||||
|
|
||||||
|
**Next.js App Router** (`app/layout.tsx`):
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { Provider } from "@/components/ui/provider"
|
||||||
|
|
||||||
|
export default function RootLayout({
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
children: React.ReactNode
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<html lang="en" suppressHydrationWarning>
|
||||||
|
<body>
|
||||||
|
<Provider>{children}</Provider>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`suppressHydrationWarning` prevents a mismatch caused by `next-themes` injecting
|
||||||
|
the color-mode class. Do **not** add `"use client"` to `layout.tsx` — the
|
||||||
|
generated provider file already has it.
|
||||||
|
|
||||||
|
**Next.js Pages Router** (`pages/_app.tsx`):
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { Provider } from "@/components/ui/provider"
|
||||||
|
|
||||||
|
export default function App({ Component, pageProps }) {
|
||||||
|
return (
|
||||||
|
<Provider>
|
||||||
|
<Component {...pageProps} />
|
||||||
|
</Provider>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Vite** (`src/main.tsx`):
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { Provider } from "./components/ui/provider"
|
||||||
|
|
||||||
|
createRoot(document.getElementById("root")!).render(
|
||||||
|
<StrictMode>
|
||||||
|
<Provider>
|
||||||
|
<App />
|
||||||
|
</Provider>
|
||||||
|
</StrictMode>,
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Manual Provider (if CLI is unavailable)
|
||||||
|
|
||||||
|
If the CLI fails, create `components/ui/provider.tsx` manually and install
|
||||||
|
`next-themes` separately:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
"use client"
|
||||||
|
import { ChakraProvider, defaultSystem } from "@chakra-ui/react"
|
||||||
|
import { ThemeProvider } from "next-themes"
|
||||||
|
|
||||||
|
export function Provider({ children }: { children: React.ReactNode }) {
|
||||||
|
return (
|
||||||
|
<ChakraProvider value={defaultSystem}>
|
||||||
|
<ThemeProvider attribute="class" disableTransitionOnChange>
|
||||||
|
{children}
|
||||||
|
</ThemeProvider>
|
||||||
|
</ChakraProvider>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Common setup issues
|
||||||
|
|
||||||
|
- **Unstyled components** — app is not wrapped in `<Provider>`. Check the import
|
||||||
|
path and that `Provider` wraps the component tree.
|
||||||
|
- **Hydration mismatch** — add `suppressHydrationWarning` to `<html>` in App
|
||||||
|
Router.
|
||||||
|
- **`next-themes` not found** — install it: `npm install next-themes` (only
|
||||||
|
needed for the manual fallback; the CLI handles it automatically).
|
||||||
|
- **`extendTheme` not exported** — this is a v2 pattern. Use `createSystem` in
|
||||||
|
v3.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 2 — Choose the right layout primitives
|
||||||
|
|
||||||
|
Reach for the right Chakra primitive rather than wrapping everything in `Box`:
|
||||||
|
|
||||||
|
| Need | Use |
|
||||||
|
| ------------------------ | --------------------------------------- |
|
||||||
|
| Vertical stack of items | `Stack` (default) or `VStack` |
|
||||||
|
| Horizontal row | `HStack` or `Flex` |
|
||||||
|
| CSS Grid | `Grid` + `GridItem` |
|
||||||
|
| Equal-column grid | `SimpleGrid columns={N}` |
|
||||||
|
| Centered page content | `Container maxW="container.lg"` |
|
||||||
|
| Full flexbox control | `Flex` with explicit props |
|
||||||
|
| Semantic section/article | `Box as="section"` / `Box as="article"` |
|
||||||
|
|
||||||
|
Avoid deep nesting. If you're three `Box` levels deep with no semantic reason,
|
||||||
|
flatten it. Prefer `gap` over margin between siblings.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 3 — Use tokens, not raw values
|
||||||
|
|
||||||
|
Chakra v3 ships semantic tokens that automatically adapt to light/dark mode.
|
||||||
|
Prefer them over hard-coded palette values — they make the component theme-aware
|
||||||
|
without any extra work.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Prefer semantic tokens
|
||||||
|
<Box bg="bg.subtle" color="fg.default" borderColor="border.subtle" />
|
||||||
|
<Text color="fg.muted" />
|
||||||
|
<Box shadow="md" rounded="lg" />
|
||||||
|
|
||||||
|
// Use colorPalette for interactive components (not colorScheme)
|
||||||
|
<Button colorPalette="blue">Submit</Button>
|
||||||
|
<Badge colorPalette="green">Active</Badge>
|
||||||
|
```
|
||||||
|
|
||||||
|
Use raw palette values (`blue.500`, `gray.100`) only when a specific color is
|
||||||
|
intentional and should not shift with color mode.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 4 — Responsive styles
|
||||||
|
|
||||||
|
Chakra uses mobile-first breakpoints. Use array or object syntax consistently:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Array: [base, sm, md, lg, xl]
|
||||||
|
<Box px={[4, 6, 8]} fontSize={["sm", "md", "lg"]} />
|
||||||
|
|
||||||
|
// Object: explicit breakpoints
|
||||||
|
<SimpleGrid columns={{ base: 1, md: 2, lg: 3 }} gap={6} />
|
||||||
|
<Stack direction={{ base: "column", md: "row" }} gap={4} />
|
||||||
|
```
|
||||||
|
|
||||||
|
Every layout component should handle at least `base` (mobile) and `md` (desktop)
|
||||||
|
breakpoints unless the request is explicitly desktop-only.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 5 — Forms
|
||||||
|
|
||||||
|
Use `Field.Root` for all form fields — it wires up label, input, error, and help
|
||||||
|
text correctly:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Field.Root invalid={!!error} required>
|
||||||
|
<Field.Label>Email address</Field.Label>
|
||||||
|
<Input type="email" placeholder="you@example.com" />
|
||||||
|
<Field.ErrorText>{error}</Field.ErrorText>
|
||||||
|
<Field.HelpText>We'll never share your email.</Field.HelpText>
|
||||||
|
</Field.Root>
|
||||||
|
```
|
||||||
|
|
||||||
|
For form submission state, use `disabled` (not `isDisabled`) on inputs and
|
||||||
|
buttons. Group related fields in a `Stack gap={4}`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 6 — Accessibility
|
||||||
|
|
||||||
|
Chakra's built-in components handle most accessibility automatically — don't
|
||||||
|
override it. The things you do need to provide:
|
||||||
|
|
||||||
|
- **Icon-only buttons**: always add `aria-label`
|
||||||
|
```tsx
|
||||||
|
<IconButton aria-label="Close dialog" icon={<CloseIcon />} />
|
||||||
|
```
|
||||||
|
- **Images**: always pass meaningful `alt` text (or `alt=""` for decorative)
|
||||||
|
- **Form labels**: use `Field.Label` or ensure `htmlFor` matches the input `id`
|
||||||
|
- **Interactive custom elements**: if you build something with `onClick` on a
|
||||||
|
`Box`, use `as="button"` or an actual `<button>` so keyboard navigation works
|
||||||
|
- **Semantic headings**: use `h1`–`h6` hierarchy; don't skip levels
|
||||||
|
- **Color contrast**: don't use light gray text on white backgrounds; rely on
|
||||||
|
semantic tokens which are contrast-tested
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 7 — Next.js: where to add `"use client"`
|
||||||
|
|
||||||
|
In Next.js App Router, Server Components are the default. Add `"use client"`
|
||||||
|
only to files that need it — not to entire layouts or pages.
|
||||||
|
|
||||||
|
A component needs `"use client"` when it:
|
||||||
|
|
||||||
|
- Uses React hooks (`useState`, `useEffect`, `useContext`, etc.)
|
||||||
|
- Handles browser events (`onClick` with state, form submission, etc.)
|
||||||
|
- Uses browser APIs
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Server Component — no directive needed
|
||||||
|
export default function ProductCard({ name, price }: Props) {
|
||||||
|
return (
|
||||||
|
<Box p={4} borderWidth={1} rounded="md">
|
||||||
|
<Text fontWeight="bold">{name}</Text>
|
||||||
|
<Text color="fg.muted">{price}</Text>
|
||||||
|
</Box>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Client Component — needs the directive
|
||||||
|
;("use client")
|
||||||
|
export function AddToCartButton({ productId }: { productId: string }) {
|
||||||
|
const [added, setAdded] = useState(false)
|
||||||
|
return (
|
||||||
|
<Button onClick={() => setAdded(true)} colorPalette="blue">
|
||||||
|
{added ? "Added!" : "Add to cart"}
|
||||||
|
</Button>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The goal is to push interactivity to the leaves — keep as much of the tree as
|
||||||
|
Server Components as possible.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 8 — When to extract components, use recipes, and customize the theme
|
||||||
|
|
||||||
|
Extract a component when the same structure appears more than twice, or when a
|
||||||
|
piece is complex enough that naming it makes the parent clearer.
|
||||||
|
|
||||||
|
Suggest a **recipe** when a component has meaningful style variants that a
|
||||||
|
developer would want to customize. Suggest a **slot recipe** for components with
|
||||||
|
multiple coordinated parts (card with header/body/footer, stat with
|
||||||
|
label/value/icon, etc.).
|
||||||
|
|
||||||
|
For deeper theming work — defining brand color tokens, semantic tokens with dark
|
||||||
|
mode values, full recipe/slot-recipe authoring, typegen, or ejecting the default
|
||||||
|
theme — read `references/theming.md` before responding. It covers the complete
|
||||||
|
`defineConfig` / `createSystem` API with full examples.
|
||||||
|
|
||||||
|
For any chart request — bar charts, area charts, line charts, pie/donut charts,
|
||||||
|
`BarList`, `BarSegment`, or anything involving `@chakra-ui/charts` — read
|
||||||
|
`references/charts.md` before responding. It covers the `useChart` hook, all
|
||||||
|
three chart types, Recharts integration, color tokens, and complete runnable
|
||||||
|
examples.
|
||||||
|
|
||||||
|
When you're unsure which component to use, or the user hasn't specified one,
|
||||||
|
read `references/component-decision-tree.md`. It covers every Chakra component
|
||||||
|
with guidance on when to choose one over a similar alternative.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Output format
|
||||||
|
|
||||||
|
Produce:
|
||||||
|
|
||||||
|
1. **Complete, runnable code** — correct imports, no placeholders like `TODO` or
|
||||||
|
`...rest of component`
|
||||||
|
2. **Proper import statements** — group Chakra imports, then local imports
|
||||||
|
3. **Component separation** — split into multiple components/files if the
|
||||||
|
component is complex or contains clearly separable parts
|
||||||
|
4. **Responsive styles** — at minimum `base` and `md` breakpoints for layout
|
||||||
|
5. **Brief explanation after the code** — 2–4 sentences on the key decisions
|
||||||
|
made (layout approach, accessibility choices, responsive strategy). Skip the
|
||||||
|
explanation if the request was trivial.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Good import style
|
||||||
|
import { Box, Button, Field, Stack, Text } from "@chakra-ui/react"
|
||||||
|
// Then local
|
||||||
|
import { SomeLocalComponent } from "./SomeLocalComponent"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## When to ask first
|
||||||
|
|
||||||
|
Build immediately if the request is clear enough to produce something useful.
|
||||||
|
Ask first when:
|
||||||
|
|
||||||
|
- The data shape is unknown and it changes the entire structure (e.g., "build a
|
||||||
|
table" — how many columns? what data?)
|
||||||
|
- There are meaningful design choices the user might care about (layout
|
||||||
|
direction, number of columns, color palette)
|
||||||
|
- The user references files or existing components you haven't seen
|
||||||
|
|
||||||
|
When in doubt, state your assumptions at the top of the response and build —
|
||||||
|
it's faster for the user to redirect from something concrete than from nothing.
|
||||||
@@ -0,0 +1,461 @@
|
|||||||
|
# Chakra UI Charts Reference
|
||||||
|
|
||||||
|
Charts live in a separate package. Install it alongside `@chakra-ui/react`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# npm
|
||||||
|
npm install @chakra-ui/charts recharts
|
||||||
|
|
||||||
|
# pnpm
|
||||||
|
pnpm add @chakra-ui/charts recharts
|
||||||
|
|
||||||
|
# yarn
|
||||||
|
yarn add @chakra-ui/charts recharts
|
||||||
|
```
|
||||||
|
|
||||||
|
Imports come from `@chakra-ui/charts`, not `@chakra-ui/react`:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { BarList, BarSegment, Chart, useChart } from "@chakra-ui/charts"
|
||||||
|
import type { BarListData, BarSegmentData } from "@chakra-ui/charts"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Three chart types
|
||||||
|
|
||||||
|
| Component | Best for | Recharts? |
|
||||||
|
| ----------------------- | ---------------------------------------------- | --------- |
|
||||||
|
| `BarList` | Rankings, comparisons (horizontal bar per row) | No |
|
||||||
|
| `BarSegment` | Composition / parts of a whole (stacked bar) | No |
|
||||||
|
| `Chart.Root` + Recharts | Line, area, bar, pie, radar, and more | Yes |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## `useChart` — the core hook
|
||||||
|
|
||||||
|
Every chart starts with `useChart`. It processes data, resolves color tokens,
|
||||||
|
and provides utilities used throughout the chart's compound components.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
const chart = useChart({
|
||||||
|
data: [...], // array of data objects
|
||||||
|
series: [...], // which keys to plot and how to color them
|
||||||
|
sort: { by: "value", direction: "desc" }, // optional
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
**`series` items:**
|
||||||
|
|
||||||
|
```ts
|
||||||
|
{
|
||||||
|
name: keyof T // data key to read values from
|
||||||
|
color: ChartColor // Chakra token ("teal.solid") or CSS color ("#FF0000")
|
||||||
|
label?: ReactNode // display name in legend/tooltip (defaults to name)
|
||||||
|
stackId?: string // for stacking in Recharts charts
|
||||||
|
yAxisId?: string // for dual-axis charts
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Color type** — accepts any Chakra color token or CSS color:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
type ChartColor = Tokens["colors"] | CSSProperties["color"]
|
||||||
|
// "teal.solid" | "blue.subtle" | "red.500" | "#FF0000" | "hsl(...)"
|
||||||
|
```
|
||||||
|
|
||||||
|
**Useful return values:**
|
||||||
|
|
||||||
|
```ts
|
||||||
|
chart.data // sorted data array
|
||||||
|
chart.series // resolved series config
|
||||||
|
chart.color("teal.solid") // resolves token → CSS color
|
||||||
|
chart.key("revenue") // safe key accessor
|
||||||
|
chart.formatNumber({ notation: "compact" })(1234567) // "1.2M"
|
||||||
|
chart.formatDate({ month: "short" })("2024-01-15") // locale-aware
|
||||||
|
chart.getTotal("revenue") // sum all values
|
||||||
|
chart.getMin("revenue") / chart.getMax("revenue")
|
||||||
|
chart.getValuePercent("revenue", value) // % of total
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## BarList
|
||||||
|
|
||||||
|
Horizontal bar chart — one bar per data row. Good for leaderboards, traffic
|
||||||
|
sources, top items.
|
||||||
|
|
||||||
|
**Data shape:**
|
||||||
|
|
||||||
|
```ts
|
||||||
|
interface BarListData {
|
||||||
|
name: string // label shown on the bar
|
||||||
|
value: number // determines bar width
|
||||||
|
href?: string // optional link
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Basic example:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { BarList, type BarListData, useChart } from "@chakra-ui/charts"
|
||||||
|
|
||||||
|
const chart = useChart<BarListData>({
|
||||||
|
data: [
|
||||||
|
{ name: "Google", value: 1_200_000 },
|
||||||
|
{ name: "Direct", value: 840_000 },
|
||||||
|
{ name: "Twitter", value: 320_000 },
|
||||||
|
{ name: "LinkedIn", value: 95_000 },
|
||||||
|
],
|
||||||
|
sort: { by: "value", direction: "desc" },
|
||||||
|
series: [{ name: "name", color: "teal.subtle" }],
|
||||||
|
})
|
||||||
|
|
||||||
|
return (
|
||||||
|
<BarList.Root chart={chart}>
|
||||||
|
<BarList.Content>
|
||||||
|
<BarList.Label title="Source" flex="1">
|
||||||
|
<BarList.Bar tooltip />
|
||||||
|
</BarList.Label>
|
||||||
|
<BarList.Label title="Visits" titleAlignment="end">
|
||||||
|
<BarList.Value />
|
||||||
|
</BarList.Label>
|
||||||
|
</BarList.Content>
|
||||||
|
</BarList.Root>
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
**With a custom value formatter:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<BarList.Value valueFormatter={(v) => `${(v / 1000).toFixed(0)}K`} />
|
||||||
|
```
|
||||||
|
|
||||||
|
**With multiple value columns:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<BarList.Label title="Visits" minW="16" titleAlignment="end">
|
||||||
|
<BarList.Value />
|
||||||
|
</BarList.Label>
|
||||||
|
<BarList.Label title="%" minW="12" titleAlignment="end">
|
||||||
|
<BarList.Value
|
||||||
|
valueFormatter={(v) =>
|
||||||
|
`${chart.getValuePercent("value", v).toFixed(0)}%`
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</BarList.Label>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## BarSegment
|
||||||
|
|
||||||
|
Single horizontal bar broken into colored segments. Good for showing how a total
|
||||||
|
is split across categories (budget, traffic, inventory).
|
||||||
|
|
||||||
|
**Data shape:**
|
||||||
|
|
||||||
|
```ts
|
||||||
|
interface BarSegmentData {
|
||||||
|
name: string // segment label
|
||||||
|
value: number // determines segment width
|
||||||
|
color: string // Chakra color token for this segment
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Basic example:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { BarSegment, useChart } from "@chakra-ui/charts"
|
||||||
|
|
||||||
|
const chart = useChart({
|
||||||
|
data: [
|
||||||
|
{ name: "Google", value: 500_000, color: "teal.solid" },
|
||||||
|
{ name: "Direct", value: 300_000, color: "blue.solid" },
|
||||||
|
{ name: "Twitter", value: 150_000, color: "purple.solid" },
|
||||||
|
{ name: "LinkedIn", value: 50_000, color: "orange.solid" },
|
||||||
|
],
|
||||||
|
sort: { by: "value", direction: "desc" },
|
||||||
|
})
|
||||||
|
|
||||||
|
return (
|
||||||
|
<BarSegment.Root chart={chart}>
|
||||||
|
<BarSegment.Content>
|
||||||
|
<BarSegment.Value />
|
||||||
|
<BarSegment.Bar tooltip />
|
||||||
|
<BarSegment.Label />
|
||||||
|
</BarSegment.Content>
|
||||||
|
<BarSegment.Legend showPercent showValue />
|
||||||
|
</BarSegment.Root>
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
**With a reference line (e.g. target):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<BarSegment.Bar tooltip>
|
||||||
|
<BarSegment.Reference label="Target" value={600_000} />
|
||||||
|
</BarSegment.Bar>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Chart.Root + Recharts
|
||||||
|
|
||||||
|
Wrapper for any Recharts chart. Handles sizing, token resolution, and styled
|
||||||
|
tooltips and legends. You still compose the chart using standard Recharts
|
||||||
|
components — `BarChart`, `AreaChart`, `LineChart`, `PieChart`, etc.
|
||||||
|
|
||||||
|
### Bar chart
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { Chart, useChart } from "@chakra-ui/charts"
|
||||||
|
import {
|
||||||
|
Bar,
|
||||||
|
BarChart,
|
||||||
|
CartesianGrid,
|
||||||
|
Legend,
|
||||||
|
Tooltip,
|
||||||
|
XAxis,
|
||||||
|
YAxis,
|
||||||
|
} from "recharts"
|
||||||
|
|
||||||
|
const chart = useChart({
|
||||||
|
data: [
|
||||||
|
{ month: "Jan", revenue: 186, expenses: 80 },
|
||||||
|
{ month: "Feb", revenue: 165, expenses: 95 },
|
||||||
|
{ month: "Mar", revenue: 210, expenses: 110 },
|
||||||
|
],
|
||||||
|
series: [
|
||||||
|
{ name: "revenue", color: "teal.solid" },
|
||||||
|
{ name: "expenses", color: "orange.solid" },
|
||||||
|
],
|
||||||
|
})
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Chart.Root maxH="sm" chart={chart}>
|
||||||
|
<BarChart data={chart.data}>
|
||||||
|
<CartesianGrid stroke={chart.color("border.muted")} vertical={false} />
|
||||||
|
<XAxis dataKey={chart.key("month")} />
|
||||||
|
<YAxis />
|
||||||
|
<Tooltip cursor={false} content={<Chart.Tooltip />} />
|
||||||
|
<Legend content={<Chart.Legend />} />
|
||||||
|
{chart.series.map((item) => (
|
||||||
|
<Bar
|
||||||
|
key={item.name}
|
||||||
|
dataKey={chart.key(item.name)}
|
||||||
|
fill={chart.color(item.color)}
|
||||||
|
radius={4}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</BarChart>
|
||||||
|
</Chart.Root>
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Area chart
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { Area, AreaChart, CartesianGrid, Tooltip, XAxis } from "recharts"
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Chart.Root maxH="sm" chart={chart}>
|
||||||
|
<AreaChart data={chart.data}>
|
||||||
|
<defs>
|
||||||
|
{chart.series.map((item) => (
|
||||||
|
<Chart.Gradient
|
||||||
|
key={item.name}
|
||||||
|
id={item.name}
|
||||||
|
stops={[
|
||||||
|
{ offset: "0%", color: item.color, opacity: 0.2 },
|
||||||
|
{ offset: "100%", color: item.color, opacity: 0 },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</defs>
|
||||||
|
<CartesianGrid stroke={chart.color("border.muted")} vertical={false} />
|
||||||
|
<XAxis dataKey={chart.key("month")} />
|
||||||
|
<Tooltip cursor={false} content={<Chart.Tooltip />} />
|
||||||
|
{chart.series.map((item) => (
|
||||||
|
<Area
|
||||||
|
key={item.name}
|
||||||
|
dataKey={chart.key(item.name)}
|
||||||
|
stroke={chart.color(item.color)}
|
||||||
|
fill={`url(#${item.name})`}
|
||||||
|
stackId="a"
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</AreaChart>
|
||||||
|
</Chart.Root>
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Pie / donut chart
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { Pie, PieChart, Tooltip } from "recharts"
|
||||||
|
|
||||||
|
const chart = useChart({
|
||||||
|
data: [
|
||||||
|
{ browser: "Chrome", visitors: 275, color: "teal.solid" },
|
||||||
|
{ browser: "Safari", visitors: 200, color: "blue.solid" },
|
||||||
|
{ browser: "Firefox", visitors: 120, color: "orange.solid" },
|
||||||
|
{ browser: "Edge", visitors: 80, color: "purple.solid" },
|
||||||
|
],
|
||||||
|
series: [{ name: "visitors" }],
|
||||||
|
})
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Chart.Root maxH="sm" chart={chart}>
|
||||||
|
<PieChart>
|
||||||
|
<Tooltip content={<Chart.Tooltip hideLabel />} />
|
||||||
|
<Pie
|
||||||
|
data={chart.data}
|
||||||
|
dataKey={chart.key("visitors")}
|
||||||
|
nameKey={chart.key("browser")}
|
||||||
|
innerRadius="60%" // remove for a filled pie
|
||||||
|
paddingAngle={2}
|
||||||
|
>
|
||||||
|
{chart.data.map((item, index) => (
|
||||||
|
<Cell key={index} fill={chart.color(item.color)} />
|
||||||
|
))}
|
||||||
|
{/* Center text for donut */}
|
||||||
|
<Label
|
||||||
|
content={
|
||||||
|
<Chart.RadialText
|
||||||
|
viewBox={undefined}
|
||||||
|
title={chart.getTotal("visitors").toLocaleString()}
|
||||||
|
description="Total visitors"
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
position="center"
|
||||||
|
/>
|
||||||
|
</Pie>
|
||||||
|
</PieChart>
|
||||||
|
</Chart.Root>
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Chart sub-components
|
||||||
|
|
||||||
|
### `Chart.Tooltip`
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Tooltip
|
||||||
|
cursor={false}
|
||||||
|
content={
|
||||||
|
<Chart.Tooltip
|
||||||
|
showTotal // show sum of all series at bottom
|
||||||
|
hideLabel // hide the x-axis label row
|
||||||
|
hideSeriesLabel // hide series names
|
||||||
|
indicator="line" // "dot" | "line" | "dashed"
|
||||||
|
formatter={(value, name) => [`$${value}`, name]}
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
```
|
||||||
|
|
||||||
|
### `Chart.Legend`
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Legend
|
||||||
|
content={
|
||||||
|
<Chart.Legend
|
||||||
|
title="Channels"
|
||||||
|
interaction="click" // "hover" (default) | "click"
|
||||||
|
verticalAlign="top" // "top" | "bottom" (default)
|
||||||
|
align="right" // "left" | "center" (default) | "right"
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
```
|
||||||
|
|
||||||
|
Legend interaction highlights/dims series on hover or click.
|
||||||
|
|
||||||
|
### `Chart.Gradient`
|
||||||
|
|
||||||
|
Defines an SVG gradient for area fills. Must be inside a `<defs>` block:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<defs>
|
||||||
|
<Chart.Gradient
|
||||||
|
id="revenue-gradient"
|
||||||
|
stops={[
|
||||||
|
{ offset: "0%", color: "teal.solid", opacity: 0.3 },
|
||||||
|
{ offset: "100%", color: "teal.solid", opacity: 0 },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</defs>
|
||||||
|
|
||||||
|
<Area fill="url(#revenue-gradient)" ... />
|
||||||
|
```
|
||||||
|
|
||||||
|
### `Chart.RadialText`
|
||||||
|
|
||||||
|
Centers a title + description inside a pie or donut chart:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Label
|
||||||
|
content={
|
||||||
|
<Chart.RadialText
|
||||||
|
viewBox={undefined}
|
||||||
|
title="$1.2M"
|
||||||
|
description="Total revenue"
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
position="center"
|
||||||
|
/>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Colors and theming
|
||||||
|
|
||||||
|
All chart colors accept Chakra token strings or plain CSS colors:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// Chakra semantic tokens — respond to light/dark mode
|
||||||
|
color: "teal.solid"
|
||||||
|
color: "blue.subtle"
|
||||||
|
color: "border.muted" // useful for grid lines
|
||||||
|
|
||||||
|
// Palette steps
|
||||||
|
color: "blue.500"
|
||||||
|
|
||||||
|
// Raw CSS
|
||||||
|
color: "#3b82f6"
|
||||||
|
color: "hsl(210, 100%, 56%)"
|
||||||
|
```
|
||||||
|
|
||||||
|
Use `chart.color(token)` to resolve a token to a CSS value wherever Recharts
|
||||||
|
needs a string (e.g. `fill`, `stroke`, `CartesianGrid stroke`).
|
||||||
|
|
||||||
|
Recommended color tokens for multi-series charts:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
series: [
|
||||||
|
{ name: "a", color: "teal.solid" },
|
||||||
|
{ name: "b", color: "blue.solid" },
|
||||||
|
{ name: "c", color: "purple.solid" },
|
||||||
|
{ name: "d", color: "orange.solid" },
|
||||||
|
{ name: "e", color: "red.solid" },
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Output format
|
||||||
|
|
||||||
|
When building chart components:
|
||||||
|
|
||||||
|
1. Show the `useChart` setup and data shape first
|
||||||
|
2. Produce complete, runnable JSX with correct imports from both
|
||||||
|
`@chakra-ui/charts` and `recharts`
|
||||||
|
3. Use `chart.color("border.muted")` for grid lines so they respect dark mode
|
||||||
|
4. Default `Chart.Root` to `maxH="sm"` unless the user specifies a size
|
||||||
|
5. Include a `Tooltip` with `<Chart.Tooltip />` on every chart — it's almost
|
||||||
|
always wanted
|
||||||
|
6. Note the install command if the project doesn't already have
|
||||||
|
`@chakra-ui/charts`
|
||||||
@@ -0,0 +1,287 @@
|
|||||||
|
# Chakra UI Component Decision Tree
|
||||||
|
|
||||||
|
When the user hasn't specified a component, choose the most appropriate one
|
||||||
|
based on the guidelines below. Prefer an existing Chakra component over a custom
|
||||||
|
implementation. Match the interaction model first, then the visual treatment.
|
||||||
|
Prefer the narrowest component that fits — don't reach for `Box` when a more
|
||||||
|
specific primitive exists.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Layout and structure
|
||||||
|
|
||||||
|
- Use `Stack` (or `VStack`) for a vertical sequence of elements with consistent
|
||||||
|
spacing.
|
||||||
|
- Use `HStack` for a horizontal sequence of elements with consistent spacing.
|
||||||
|
- Use `Flex` when you need explicit control over flexbox properties (direction,
|
||||||
|
wrap, alignment).
|
||||||
|
- Use `Grid` + `GridItem` for two-dimensional layouts (rows and columns).
|
||||||
|
- Use `SimpleGrid` for equal-width columns that wrap automatically — good for
|
||||||
|
card grids and dashboards.
|
||||||
|
- Use `Container` to constrain page content to a max-width with horizontal
|
||||||
|
centering.
|
||||||
|
- Use `Center` to center content both horizontally and vertically without manual
|
||||||
|
flex setup.
|
||||||
|
- Use `AbsoluteCenter` when centering with `position: absolute` — useful for
|
||||||
|
overlays and loaders.
|
||||||
|
- Use `Card` when content is a self-contained unit that needs visual separation
|
||||||
|
(border, shadow, padding). Use `Box` only when no built-in container semantics
|
||||||
|
apply.
|
||||||
|
- Use `Wrap` for tag clouds, badge sets, or button groups that should flow and
|
||||||
|
wrap automatically.
|
||||||
|
- Use `Spacer` inside `Flex` to push elements to opposite ends.
|
||||||
|
- Use `Group` to visually merge related elements (buttons, inputs) into a single
|
||||||
|
bordered unit.
|
||||||
|
- Use `Bleed` to extend a background or image beyond the padding of its parent
|
||||||
|
container.
|
||||||
|
- Use `Splitter` when the user should be able to resize two adjacent panels.
|
||||||
|
- Use `ScrollArea` for a container that needs custom cross-browser styled
|
||||||
|
scrollbars.
|
||||||
|
- Use `AspectRatio` to lock a child element (video, image, map) to a fixed
|
||||||
|
aspect ratio.
|
||||||
|
|
||||||
|
### Stack vs Flex vs Grid
|
||||||
|
|
||||||
|
- Choose `Stack` or `HStack`/`VStack` for uniform spacing along one axis — it's
|
||||||
|
the most common case.
|
||||||
|
- Choose `Flex` when you need `flexWrap`, `justifyContent`, `alignItems`, or
|
||||||
|
other flex properties beyond spacing.
|
||||||
|
- Choose `Grid` when you need to position elements across both rows and columns
|
||||||
|
at the same time.
|
||||||
|
- Choose `SimpleGrid` when you only need responsive equal-width columns and
|
||||||
|
nothing more.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Typography
|
||||||
|
|
||||||
|
- Use `Heading` for page and section titles (`h1`–`h6`). Don't use `Text` as a
|
||||||
|
heading shortcut.
|
||||||
|
- Use `Text` for body copy, labels, and descriptive text.
|
||||||
|
- Use `Span` for inline styled text inside a paragraph.
|
||||||
|
- Use `Em` and `Strong` for semantically emphasized or important text.
|
||||||
|
- Use `Mark` for highlighted text (e.g. search result matches).
|
||||||
|
- Use `Code` for short inline code snippets.
|
||||||
|
- Use `CodeBlock` for multi-line code with copy button and optional collapse —
|
||||||
|
not for single-line snippets.
|
||||||
|
- Use `Kbd` to display keyboard shortcuts.
|
||||||
|
- Use `Blockquote` for pull quotes with attribution.
|
||||||
|
- Use `Highlight` to highlight matching substrings dynamically in text.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Actions and links
|
||||||
|
|
||||||
|
- Use `Button` for primary and secondary actions (form submissions,
|
||||||
|
confirmations, key page actions).
|
||||||
|
- Use `IconButton` for icon-only actions — always provide `aria-label`.
|
||||||
|
- Use `CloseButton` for dismiss/close actions in dialogs, drawers, and toasts.
|
||||||
|
- Use `ButtonGroup` to group related actions (e.g. Save / Cancel) with
|
||||||
|
consistent sizing and variant.
|
||||||
|
- Use `Link` for text navigation — inline within a sentence or standalone. Use
|
||||||
|
`asChild` with Next.js `<Link>` in App Router projects.
|
||||||
|
- Use `LinkBox` + `LinkOverlay` to make an entire card or row clickable while
|
||||||
|
preserving accessible markup.
|
||||||
|
- Use `Toggle` when a button should visually represent an on/off pressed state.
|
||||||
|
- Use `Switch` (not `Toggle`) when the interaction is a persistent on/off
|
||||||
|
setting (e.g. enable notifications).
|
||||||
|
- Use `DownloadTrigger` for file download buttons.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Choosing from options
|
||||||
|
|
||||||
|
- Use `Switch` for turning a single setting on or off.
|
||||||
|
- Use `Checkbox` for a single independent yes/no option. Use `CheckboxGroup` for
|
||||||
|
a set of independent options where many can be selected.
|
||||||
|
- Use `CheckboxCard` over `Checkbox` when the option needs a title, description,
|
||||||
|
or more visual emphasis.
|
||||||
|
- Use `RadioGroup` for mutually exclusive options when 2–4 options should always
|
||||||
|
be visible.
|
||||||
|
- Use `RadioCard` over `RadioGroup` when each option benefits from a
|
||||||
|
description, icon, or richer presentation.
|
||||||
|
- Use `SegmentGroup` for a compact mutually exclusive mode/view switch
|
||||||
|
(iOS-style segmented control) — typically 2–4 options.
|
||||||
|
- Use `NativeSelect` for mobile-first dropdowns where the platform picker is
|
||||||
|
preferred.
|
||||||
|
- Use `Select` for styled dropdowns with full design control — prefer over
|
||||||
|
`NativeSelect` on desktop.
|
||||||
|
- Use `Combobox` when the user should type to filter a long list or search
|
||||||
|
options — prefer over `Select` for lists longer than ~15 items.
|
||||||
|
- Use `Listbox` when options must always be visible and scrollable without a
|
||||||
|
dropdown trigger.
|
||||||
|
- Use `TagsInput` for entering multiple free-form or autocompleted values
|
||||||
|
(skills, labels, emails).
|
||||||
|
- Use `RatingGroup` for star or point ratings.
|
||||||
|
|
||||||
|
### Select vs Combobox vs NativeSelect
|
||||||
|
|
||||||
|
- Choose `NativeSelect` for mobile-first or form-heavy interfaces where native
|
||||||
|
picker behavior is expected.
|
||||||
|
- Choose `Select` for styled dropdowns on desktop with a known, bounded list.
|
||||||
|
- Choose `Combobox` when filtering/searching is important or the list is long.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Text and value input
|
||||||
|
|
||||||
|
- Use `Input` for single-line plain text.
|
||||||
|
- Use `Textarea` for multi-line text.
|
||||||
|
- Use `NumberInput` for numeric entry with increment/decrement controls.
|
||||||
|
- Use `Slider` for adjusting a value when direct manipulation is preferred over
|
||||||
|
exact entry. Use a range slider (dual thumbs) for min/max ranges.
|
||||||
|
- Use `PinInput` for fixed-length codes — OTP verification, PIN entry. It
|
||||||
|
auto-advances focus between fields.
|
||||||
|
- Use `Editable` for click-to-edit inline text — useful for titles,
|
||||||
|
descriptions, and table cells.
|
||||||
|
- Use `DatePicker` when a calendar popover should assist with date selection.
|
||||||
|
- Use `ColorPicker` for full color selection with RGB/HSL/hex modes and
|
||||||
|
eyedropper.
|
||||||
|
- Use `FileUpload` for file selection with drag-and-drop and preview.
|
||||||
|
- Use `Clipboard` for copy-to-clipboard functionality with visual feedback.
|
||||||
|
- Use `Field.Root` to wrap every form input — it wires up the label, helper
|
||||||
|
text, error text, and required indicator correctly.
|
||||||
|
- Use `InputGroup` to attach prefix/suffix addons (icons, currency symbols,
|
||||||
|
units) to an `Input`.
|
||||||
|
- Use `Fieldset` to group semantically related form fields under a shared
|
||||||
|
legend.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Overlays and pop-ups
|
||||||
|
|
||||||
|
- Use `Tooltip` for a short text description of a focusable element. Don't put
|
||||||
|
interactive content in a tooltip.
|
||||||
|
- Use `HoverCard` for richer preview content on hover (user profiles, link
|
||||||
|
previews) — more than a tooltip, less than a popover.
|
||||||
|
- Use `Popover` for interactive contextual content anchored to a trigger —
|
||||||
|
forms, filters, settings panels.
|
||||||
|
- Use `Dialog` for modal tasks that require user attention before continuing.
|
||||||
|
- Use `Drawer` for off-canvas panels — navigation, detail views, settings — when
|
||||||
|
modal behavior is needed but the content is beside rather than over the page.
|
||||||
|
- Use `Toast` for brief transient feedback after an action (saved, error,
|
||||||
|
copied). Use the `Toaster` component to render stacked toasts.
|
||||||
|
- Use `ActionBar` for mobile-style bulk action bars that appear after selection.
|
||||||
|
- Use `Menu` for action menus triggered by a button — "more options",
|
||||||
|
right-click menus. Use `Menu.CheckboxItem` and `Menu.RadioItem` for
|
||||||
|
toggle/selection actions within a menu.
|
||||||
|
|
||||||
|
### Tooltip vs HoverCard vs Popover
|
||||||
|
|
||||||
|
- Choose `Tooltip` for a single line of non-interactive help text.
|
||||||
|
- Choose `HoverCard` for hover-triggered preview cards with structured content.
|
||||||
|
- Choose `Popover` when the floating content needs to be interactive (has
|
||||||
|
buttons, inputs, or links).
|
||||||
|
|
||||||
|
### Dialog vs Drawer
|
||||||
|
|
||||||
|
- Choose `Dialog` when the overlay should be centered, blocking, and focus
|
||||||
|
attention on a specific task or confirmation.
|
||||||
|
- Choose `Drawer` when the content slides in from an edge and relates to what's
|
||||||
|
already on screen (details, navigation, filters).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Disclosure and navigation
|
||||||
|
|
||||||
|
- Use `Accordion` for a set of related collapsible sections where only one (or a
|
||||||
|
few) should be open at a time — FAQs, grouped settings.
|
||||||
|
- Use `Collapsible` for a single expandable section — don't use `Accordion` with
|
||||||
|
one item.
|
||||||
|
- Use `Tabs` for peer content panels where switching shows one panel at a time —
|
||||||
|
prefer for horizontal layouts.
|
||||||
|
- Use `SegmentGroup` instead of `Tabs` when switching modes or views rather than
|
||||||
|
showing different full content panels.
|
||||||
|
- Use `Steps` for multi-step wizards and onboarding flows — shows progress and
|
||||||
|
allows back/next navigation.
|
||||||
|
- Use `Breadcrumb` to show the user's location in a hierarchy.
|
||||||
|
- Use `Pagination` for navigating paged datasets.
|
||||||
|
- Use `Menu` for dropdown navigation menus.
|
||||||
|
- Use `TreeView` when a file-system-style hierarchy must stay visible and
|
||||||
|
expandable in place.
|
||||||
|
|
||||||
|
### Accordion vs Tabs vs Collapsible
|
||||||
|
|
||||||
|
- Choose `Accordion` for vertically stacked collapsible sections (FAQs, settings
|
||||||
|
groups).
|
||||||
|
- Choose `Tabs` for horizontal peer sections where all tabs are always visible.
|
||||||
|
- Choose `Collapsible` for a single show/hide section — not a group.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Data display
|
||||||
|
|
||||||
|
- Use `Table` for structured tabular data with rows and columns — sortable
|
||||||
|
headers, dense comparison.
|
||||||
|
- Use `DataList` for key-value pairs (user profile details, metadata) — not true
|
||||||
|
tabular data.
|
||||||
|
- Use `Stat` + `StatGroup` for KPI metrics and dashboard numbers with up/down
|
||||||
|
indicators.
|
||||||
|
- Use `Timeline` for chronological events, changelogs, or process steps.
|
||||||
|
- Use `Badge` for compact non-removable status labels (Active, Beta, New).
|
||||||
|
- Use `Tag` over `Badge` when the label should be removable or interactive.
|
||||||
|
- Use `Avatar` + `AvatarGroup` for user profile pictures with fallback initials
|
||||||
|
or icon.
|
||||||
|
- Use `Carousel` for image galleries, feature showcases, or content sliders.
|
||||||
|
- Use `QrCode` to render a QR code from a string value.
|
||||||
|
- Use `ColorSwatch` to display a color value visually.
|
||||||
|
|
||||||
|
### Table vs DataList
|
||||||
|
|
||||||
|
- Choose `Table` when data has multiple comparable columns and rows.
|
||||||
|
- Choose `DataList` for a single record's attributes displayed as label/value
|
||||||
|
pairs.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Feedback and status
|
||||||
|
|
||||||
|
- Use `Alert` for persistent in-page messages (warnings, info, errors) that are
|
||||||
|
part of the page layout.
|
||||||
|
- Use `Toast` for transient post-action feedback — it disappears automatically.
|
||||||
|
- Use `EmptyState` for no-data and no-results states — provides structured
|
||||||
|
layout for illustration, title, description, and actions.
|
||||||
|
- Use `Spinner` for indeterminate loading — content is fetching, duration
|
||||||
|
unknown.
|
||||||
|
- Use `Skeleton` for loading placeholders that approximate the shape of incoming
|
||||||
|
content.
|
||||||
|
- Use `Progress` for a linear progress bar on an operation with a known
|
||||||
|
completion percentage.
|
||||||
|
- Use `ProgressCircle` for the same use case when a circular indicator fits the
|
||||||
|
layout better.
|
||||||
|
- Use `Loader` as an alternative to `Spinner` for a different visual style of
|
||||||
|
indeterminate loading.
|
||||||
|
|
||||||
|
### Alert vs Toast vs EmptyState
|
||||||
|
|
||||||
|
- Choose `Alert` when the message is persistent and tied to content on the
|
||||||
|
current view.
|
||||||
|
- Choose `Toast` when the message is temporary and triggered by a user action.
|
||||||
|
- Choose `EmptyState` when there is no content to display and you want to
|
||||||
|
explain why and offer a next action.
|
||||||
|
|
||||||
|
### Spinner vs Skeleton vs Progress
|
||||||
|
|
||||||
|
- Choose `Spinner` when loading is happening and the layout isn't known yet.
|
||||||
|
- Choose `Skeleton` when the layout is known — show placeholder shapes that
|
||||||
|
match the expected content.
|
||||||
|
- Choose `Progress` when the operation has a measurable percentage.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Utilities
|
||||||
|
|
||||||
|
- Use `VisuallyHidden` for screen-reader-only text — skip links, icon button
|
||||||
|
labels added outside the button.
|
||||||
|
- Use `SkipNav` to add a skip-to-main-content accessibility link.
|
||||||
|
- Use `Portal` when a component must render outside its DOM parent to avoid
|
||||||
|
z-index or overflow clipping issues.
|
||||||
|
- Use `FocusTrap` to constrain keyboard focus within a region (custom modals,
|
||||||
|
custom drawers).
|
||||||
|
- Use `Presence` to animate components on mount and unmount.
|
||||||
|
- Use `Show` / `Hide` for responsive conditional rendering based on breakpoints.
|
||||||
|
- Use `For` as a typed loop utility when rendering lists of components.
|
||||||
|
- Use `ClientOnly` to prevent SSR hydration mismatches for browser-only content.
|
||||||
|
- Use `FormatNumber` / `FormatByte` for locale-aware number and file-size
|
||||||
|
formatting.
|
||||||
|
- Use `Marquee` for scrolling announcement banners or news tickers.
|
||||||
@@ -0,0 +1,331 @@
|
|||||||
|
# Chakra UI Theming Reference
|
||||||
|
|
||||||
|
Use v3 patterns (`defineConfig`, `createSystem`, `defineRecipe`,
|
||||||
|
`defineSlotRecipe`) by default. Only use v2 patterns (`extendTheme`,
|
||||||
|
`styleConfig`) if the project is explicitly on v2.
|
||||||
|
|
||||||
|
Before starting, check `package.json` for the Chakra UI version and look for an
|
||||||
|
existing theme file (`theme.ts`, `system.ts`) to understand what's already
|
||||||
|
defined.
|
||||||
|
|
||||||
|
Clarify scope when needed:
|
||||||
|
|
||||||
|
- **Full design system** — tokens, semantic tokens, and component recipes from
|
||||||
|
scratch
|
||||||
|
- **Partial update** — adding or changing specific tokens or recipes
|
||||||
|
- **Single recipe** — one component's styles with variants
|
||||||
|
- **Typegen only** — running `@chakra-ui/cli typegen` after custom additions
|
||||||
|
|
||||||
|
If the user says "add my brand colors" without specifying the colors, ask first.
|
||||||
|
A partial answer is worse than pausing to clarify.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## System setup: `defineConfig` and `createSystem`
|
||||||
|
|
||||||
|
All theming in v3 starts with `createSystem`. Use `defineConfig` to author
|
||||||
|
customizations, then merge with `defaultConfig`:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// theme.ts
|
||||||
|
import { createSystem, defaultConfig, defineConfig } from "@chakra-ui/react"
|
||||||
|
|
||||||
|
const config = defineConfig({
|
||||||
|
theme: {
|
||||||
|
tokens: {
|
||||||
|
/* ... */
|
||||||
|
},
|
||||||
|
semanticTokens: {
|
||||||
|
/* ... */
|
||||||
|
},
|
||||||
|
recipes: {
|
||||||
|
/* ... */
|
||||||
|
},
|
||||||
|
slotRecipes: {
|
||||||
|
/* ... */
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
export const system = createSystem(defaultConfig, config)
|
||||||
|
```
|
||||||
|
|
||||||
|
Pass `system` to `ChakraProvider`:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// components/ui/provider.tsx
|
||||||
|
"use client"
|
||||||
|
import { system } from "@/theme"
|
||||||
|
import { ChakraProvider } from "@chakra-ui/react"
|
||||||
|
|
||||||
|
export function Provider({ children }) {
|
||||||
|
return <ChakraProvider value={system}>{children}</ChakraProvider>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Tokens
|
||||||
|
|
||||||
|
Tokens are the raw, concrete values in your design system — the foundation
|
||||||
|
everything else references.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
const config = defineConfig({
|
||||||
|
theme: {
|
||||||
|
tokens: {
|
||||||
|
colors: {
|
||||||
|
brand: {
|
||||||
|
50: { value: "#eff6ff" },
|
||||||
|
100: { value: "#dbeafe" },
|
||||||
|
200: { value: "#bfdbfe" },
|
||||||
|
500: { value: "#3b82f6" },
|
||||||
|
600: { value: "#2563eb" },
|
||||||
|
700: { value: "#1d4ed8" },
|
||||||
|
900: { value: "#1e3a8a" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
fonts: {
|
||||||
|
heading: { value: "var(--font-geist-sans), sans-serif" },
|
||||||
|
body: { value: "var(--font-geist-sans), sans-serif" },
|
||||||
|
mono: { value: "var(--font-geist-mono), monospace" },
|
||||||
|
},
|
||||||
|
fontSizes: {
|
||||||
|
xs: { value: "0.75rem" },
|
||||||
|
sm: { value: "0.875rem" },
|
||||||
|
md: { value: "1rem" },
|
||||||
|
lg: { value: "1.125rem" },
|
||||||
|
xl: { value: "1.25rem" },
|
||||||
|
"2xl": { value: "1.5rem" },
|
||||||
|
},
|
||||||
|
radii: {
|
||||||
|
sm: { value: "0.25rem" },
|
||||||
|
md: { value: "0.375rem" },
|
||||||
|
lg: { value: "0.5rem" },
|
||||||
|
xl: { value: "0.75rem" },
|
||||||
|
full: { value: "9999px" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Use scale-based keys for palettes (`50`, `100`, …, `900`) and semantic keys for
|
||||||
|
single values (`sm`, `md`, `lg`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Semantic tokens
|
||||||
|
|
||||||
|
Semantic tokens reference base tokens and assign _meaning_ to them. Their key
|
||||||
|
feature: different values per color mode, making dark mode automatic.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
const config = defineConfig({
|
||||||
|
theme: {
|
||||||
|
semanticTokens: {
|
||||||
|
colors: {
|
||||||
|
"brand.solid": {
|
||||||
|
value: { base: "{colors.brand.600}", _dark: "{colors.brand.400}" },
|
||||||
|
},
|
||||||
|
"brand.muted": {
|
||||||
|
value: { base: "{colors.brand.100}", _dark: "{colors.brand.900}" },
|
||||||
|
},
|
||||||
|
"brand.subtle": {
|
||||||
|
value: { base: "{colors.brand.50}", _dark: "{colors.brand.950}" },
|
||||||
|
},
|
||||||
|
|
||||||
|
"bg.default": { value: { base: "white", _dark: "{colors.gray.900}" } },
|
||||||
|
"bg.subtle": {
|
||||||
|
value: { base: "{colors.gray.50}", _dark: "{colors.gray.800}" },
|
||||||
|
},
|
||||||
|
"bg.muted": {
|
||||||
|
value: { base: "{colors.gray.100}", _dark: "{colors.gray.700}" },
|
||||||
|
},
|
||||||
|
|
||||||
|
"fg.default": { value: { base: "{colors.gray.900}", _dark: "white" } },
|
||||||
|
"fg.muted": {
|
||||||
|
value: { base: "{colors.gray.600}", _dark: "{colors.gray.400}" },
|
||||||
|
},
|
||||||
|
"fg.subtle": {
|
||||||
|
value: { base: "{colors.gray.400}", _dark: "{colors.gray.600}" },
|
||||||
|
},
|
||||||
|
|
||||||
|
"border.default": {
|
||||||
|
value: { base: "{colors.gray.200}", _dark: "{colors.gray.700}" },
|
||||||
|
},
|
||||||
|
"border.muted": {
|
||||||
|
value: { base: "{colors.gray.100}", _dark: "{colors.gray.800}" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Components that use `bg="bg.subtle"` instead of `bg="gray.50"` automatically get
|
||||||
|
the correct dark mode value — no conditional logic needed. Build on semantic
|
||||||
|
tokens wherever possible.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Recipes (single-component styles)
|
||||||
|
|
||||||
|
Recipes replace `styleConfig` from v2. Use them when a single component has
|
||||||
|
meaningful style variants that developers will reuse across the project.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { defineRecipe } from "@chakra-ui/react"
|
||||||
|
|
||||||
|
export const badgeRecipe = defineRecipe({
|
||||||
|
base: {
|
||||||
|
display: "inline-flex",
|
||||||
|
alignItems: "center",
|
||||||
|
px: 2,
|
||||||
|
py: 0.5,
|
||||||
|
borderRadius: "full",
|
||||||
|
fontSize: "xs",
|
||||||
|
fontWeight: "medium",
|
||||||
|
},
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
solid: { bg: "colorPalette.500", color: "white" },
|
||||||
|
subtle: { bg: "colorPalette.100", color: "colorPalette.800" },
|
||||||
|
outline: {
|
||||||
|
borderWidth: 1,
|
||||||
|
borderColor: "colorPalette.500",
|
||||||
|
color: "colorPalette.600",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
size: {
|
||||||
|
sm: { px: 1.5, py: 0.5, fontSize: "2xs" },
|
||||||
|
md: { px: 2, py: 0.5, fontSize: "xs" },
|
||||||
|
lg: { px: 3, py: 1, fontSize: "sm" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: { variant: "subtle", size: "md" },
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Register in the theme config:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
const config = defineConfig({ theme: { recipes: { badge: badgeRecipe } } })
|
||||||
|
```
|
||||||
|
|
||||||
|
`colorPalette` inside a recipe is a placeholder — it resolves to whatever
|
||||||
|
`colorPalette` prop the consumer passes (`colorPalette="blue"` → `blue.500`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Slot recipes (multi-part components)
|
||||||
|
|
||||||
|
Slot recipes replace `multiStyleConfig` from v2. Use them when a component has
|
||||||
|
multiple coordinated parts that all respond to the same variants.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { defineSlotRecipe } from "@chakra-ui/react"
|
||||||
|
|
||||||
|
export const cardSlotRecipe = defineSlotRecipe({
|
||||||
|
slots: ["root", "header", "body", "footer", "title"],
|
||||||
|
base: {
|
||||||
|
root: { bg: "bg.surface", rounded: "xl", overflow: "hidden", shadow: "sm" },
|
||||||
|
header: { px: 6, py: 4, borderBottomWidth: 1, borderColor: "border.muted" },
|
||||||
|
body: { px: 6, py: 4 },
|
||||||
|
footer: { px: 6, py: 4, borderTopWidth: 1, borderColor: "border.muted" },
|
||||||
|
title: { fontSize: "lg", fontWeight: "semibold", color: "fg.default" },
|
||||||
|
},
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
elevated: { root: { shadow: "md" } },
|
||||||
|
outline: {
|
||||||
|
root: { shadow: "none", borderWidth: 1, borderColor: "border.default" },
|
||||||
|
},
|
||||||
|
filled: { root: { bg: "bg.subtle", shadow: "none" } },
|
||||||
|
},
|
||||||
|
size: {
|
||||||
|
sm: {
|
||||||
|
root: { rounded: "lg" },
|
||||||
|
body: { px: 4, py: 3 },
|
||||||
|
header: { px: 4, py: 3 },
|
||||||
|
},
|
||||||
|
md: {},
|
||||||
|
lg: { body: { px: 8, py: 6 }, header: { px: 8, py: 6 } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: { variant: "elevated", size: "md" },
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Register:
|
||||||
|
`const config = defineConfig({ theme: { slotRecipes: { card: cardSlotRecipe } } })`
|
||||||
|
|
||||||
|
Consume with `useSlotRecipe`:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { useSlotRecipe } from "@chakra-ui/react"
|
||||||
|
|
||||||
|
function Card({ variant = "elevated", size = "md", children }) {
|
||||||
|
const recipe = useSlotRecipe({ key: "card" })
|
||||||
|
const styles = recipe({ variant, size })
|
||||||
|
return <Box css={styles.root}>{children}</Box>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Typegen
|
||||||
|
|
||||||
|
Run typegen after adding custom tokens, semantic tokens, recipes, or slot
|
||||||
|
recipes. Without it, TypeScript won't know your custom values exist.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx @chakra-ui/cli typegen ./theme.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
| Flag | Effect |
|
||||||
|
| ------------------- | ------------------------------------------------------------- |
|
||||||
|
| `--strict` | Strict literal types for variant and size props (recommended) |
|
||||||
|
| `--watch` | Re-runs automatically whenever the theme file changes |
|
||||||
|
| `--outdir <dir>` | Custom output directory for generated types |
|
||||||
|
| `--tsconfig <path>` | Path to tsconfig when using path aliases |
|
||||||
|
|
||||||
|
For active development: `npx @chakra-ui/cli typegen ./theme.ts --watch`
|
||||||
|
|
||||||
|
Typegen is required when you've added custom color tokens, semantic tokens,
|
||||||
|
spacing/font/radius tokens, or new recipes or slot recipes.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Ejecting the default theme
|
||||||
|
|
||||||
|
For full control over Chakra's built-in tokens, recipes, and styles:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx @chakra-ui/cli eject
|
||||||
|
```
|
||||||
|
|
||||||
|
Writes the complete default theme into a `theme/` directory (`--outdir <dir>` to
|
||||||
|
override), including separate files for tokens, semantic tokens, recipes, slot
|
||||||
|
recipes, text styles, layer styles, and animation styles — all as editable
|
||||||
|
`defineConfig` exports.
|
||||||
|
|
||||||
|
Use `eject` when modifying built-in component recipes or replacing large parts
|
||||||
|
of the default token scale. For smaller customizations (adding brand colors,
|
||||||
|
overriding a few tokens), extending with `defineConfig` is simpler.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Output format
|
||||||
|
|
||||||
|
Produce:
|
||||||
|
|
||||||
|
1. **Complete theme config** — `defineConfig` with all relevant sections
|
||||||
|
2. **Proper imports** — `defineConfig`, `createSystem`, `defineRecipe`, etc.
|
||||||
|
from `@chakra-ui/react`
|
||||||
|
3. **Provider wiring** — how to pass `system` to `ChakraProvider` if needed
|
||||||
|
4. **Usage examples** — show tokens/recipes consumed in a component
|
||||||
|
5. **Typegen reminder** — note when to run typegen
|
||||||
|
|
||||||
|
Brief explanation after the code (2–4 sentences) on key decisions. Skip for
|
||||||
|
trivial requests.
|
||||||
@@ -0,0 +1,494 @@
|
|||||||
|
---
|
||||||
|
name: chakra-ui-migrate
|
||||||
|
description: >
|
||||||
|
Migrate Chakra UI projects from v2 to v3, covering package changes, codemods,
|
||||||
|
provider setup, color mode, prop renaming, compound components, theming,
|
||||||
|
recipes, and Next.js updates. Use this skill whenever a user is upgrading
|
||||||
|
Chakra UI versions, encountering breaking changes after an upgrade, converting
|
||||||
|
old v2 patterns (ColorModeScript, useColorModeValue, styleConfig, extendTheme,
|
||||||
|
isDisabled, colorScheme, @chakra-ui/icons, framer-motion dependency), fixing
|
||||||
|
compound component patterns, or asking about differences between Chakra UI v2
|
||||||
|
and v3 — even if they don't say "migrate" or "upgrade" explicitly.
|
||||||
|
---
|
||||||
|
|
||||||
|
# Chakra UI Migration: v2 → v3
|
||||||
|
|
||||||
|
You are guiding a developer through migrating their project from Chakra UI v2 to
|
||||||
|
v3. Work through the steps below in order. Inspect the project first — never
|
||||||
|
guess the package versions or framework.
|
||||||
|
|
||||||
|
> **Node requirement:** Chakra UI v3 requires Node >= 20.x. Confirm before
|
||||||
|
> proceeding if the environment is uncertain.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 1 — Inspect the project
|
||||||
|
|
||||||
|
Read these files to understand the current state:
|
||||||
|
|
||||||
|
```
|
||||||
|
package.json
|
||||||
|
```
|
||||||
|
|
||||||
|
Look for:
|
||||||
|
|
||||||
|
- Current `@chakra-ui/react` version (v2.x vs v3.x)
|
||||||
|
- Related packages: `@chakra-ui/icons`, `@chakra-ui/hooks`,
|
||||||
|
`@chakra-ui/next-js`, `@emotion/styled`, `framer-motion`
|
||||||
|
- Framework: Next.js (App Router or Pages Router), Vite, plain React
|
||||||
|
- Package manager (from lockfiles: `pnpm-lock.yaml`, `yarn.lock`, `bun.lock`,
|
||||||
|
`package-lock.json`)
|
||||||
|
|
||||||
|
Also spot-check key files when helpful:
|
||||||
|
|
||||||
|
- Provider / theme setup (`_app.tsx`, `layout.tsx`, `theme.ts`)
|
||||||
|
- Color mode usage (`ColorModeScript`, `useColorMode`, `useColorModeValue`)
|
||||||
|
- Any component files showing heavy v2 patterns
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 2 — Update packages
|
||||||
|
|
||||||
|
### Remove v2-only dependencies
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# npm
|
||||||
|
npm uninstall @chakra-ui/icons @chakra-ui/hooks @chakra-ui/next-js @emotion/styled framer-motion
|
||||||
|
|
||||||
|
# pnpm
|
||||||
|
pnpm remove @chakra-ui/icons @chakra-ui/hooks @chakra-ui/next-js @emotion/styled framer-motion
|
||||||
|
|
||||||
|
# yarn
|
||||||
|
yarn remove @chakra-ui/icons @chakra-ui/hooks @chakra-ui/next-js @emotion/styled framer-motion
|
||||||
|
```
|
||||||
|
|
||||||
|
`@emotion/styled` and `framer-motion` are no longer required in v3.
|
||||||
|
|
||||||
|
### Install v3 core packages
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# npm
|
||||||
|
npm install @chakra-ui/react @emotion/react
|
||||||
|
|
||||||
|
# pnpm
|
||||||
|
pnpm add @chakra-ui/react @emotion/react
|
||||||
|
|
||||||
|
# yarn
|
||||||
|
yarn add @chakra-ui/react @emotion/react
|
||||||
|
```
|
||||||
|
|
||||||
|
### Replacements for removed packages
|
||||||
|
|
||||||
|
| Removed | Replacement |
|
||||||
|
| -------------------- | -------------------------------------------- |
|
||||||
|
| `@chakra-ui/icons` | `lucide-react` or `react-icons` |
|
||||||
|
| `@chakra-ui/hooks` | `react-use` or `usehooks-ts` |
|
||||||
|
| `@chakra-ui/next-js` | `asChild` prop pattern (see Next.js section) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 3 — Run the codemod
|
||||||
|
|
||||||
|
The official codemod handles most mechanical changes: component renames, prop
|
||||||
|
updates, import rewrites, and compound component restructuring. It does not
|
||||||
|
replace manual review — plan to audit the output.
|
||||||
|
|
||||||
|
**Dry run first (no files changed):**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx @chakra-ui/codemod upgrade --dry
|
||||||
|
```
|
||||||
|
|
||||||
|
Review what it proposes. When satisfied:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx @chakra-ui/codemod upgrade
|
||||||
|
```
|
||||||
|
|
||||||
|
After the codemod, commit the changes before making manual edits so you have a
|
||||||
|
clean diff to work from.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 4 — Update the Provider
|
||||||
|
|
||||||
|
### Old v2 pattern
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// v2
|
||||||
|
import { ChakraProvider } from "@chakra-ui/react"
|
||||||
|
import theme from "./theme"
|
||||||
|
|
||||||
|
;<ChakraProvider theme={theme}>{children}</ChakraProvider>
|
||||||
|
```
|
||||||
|
|
||||||
|
### New v3 pattern (using Chakra CLI snippets)
|
||||||
|
|
||||||
|
Generate the provider and component snippets:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx @chakra-ui/cli snippet add
|
||||||
|
```
|
||||||
|
|
||||||
|
This creates `components/ui/provider.tsx` (plus `toaster` and `tooltip`
|
||||||
|
snippets) and automatically installs required npm dependencies — including
|
||||||
|
`next-themes`. Import and use it:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// v3 — app/layout.tsx (Next.js App Router)
|
||||||
|
import { Provider } from "@/components/ui/provider"
|
||||||
|
|
||||||
|
;<html lang="en" suppressHydrationWarning>
|
||||||
|
<body>
|
||||||
|
<Provider>{children}</Provider>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
```
|
||||||
|
|
||||||
|
The `Provider` file includes `"use client"` — do not add it to `layout.tsx`. See
|
||||||
|
the Next.js section for Pages Router placement.
|
||||||
|
|
||||||
|
### Custom theme in v3
|
||||||
|
|
||||||
|
Replace `extendTheme` with `createSystem`:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// v2
|
||||||
|
import { extendTheme } from "@chakra-ui/react"
|
||||||
|
// v3
|
||||||
|
import { createSystem, defaultConfig, defineConfig } from "@chakra-ui/react"
|
||||||
|
|
||||||
|
export const theme = extendTheme({ colors: { brand: { 500: "#2196f3" } } })
|
||||||
|
|
||||||
|
const config = defineConfig({
|
||||||
|
theme: { tokens: { colors: { brand: { 500: { value: "#2196f3" } } } } },
|
||||||
|
})
|
||||||
|
export const system = createSystem(defaultConfig, config)
|
||||||
|
```
|
||||||
|
|
||||||
|
Pass `system` to `ChakraProvider` via `value={system}`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 5 — Color mode migration
|
||||||
|
|
||||||
|
### Remove all v2 color mode patterns
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// REMOVE these v2 imports and usages:
|
||||||
|
import { ColorModeScript } from "@chakra-ui/react"
|
||||||
|
// ❌
|
||||||
|
import { useColorMode } from "@chakra-ui/react"
|
||||||
|
// ❌ (use next-themes)
|
||||||
|
import { useColorModeValue } from "@chakra-ui/react"
|
||||||
|
// ❌ (use CSS tokens)
|
||||||
|
import { DarkMode, LightMode } from "@chakra-ui/react"
|
||||||
|
|
||||||
|
// ❌
|
||||||
|
|
||||||
|
// Also remove from _document.tsx:
|
||||||
|
;<ColorModeScript initialColorMode={theme.config.initialColorMode} /> // ❌
|
||||||
|
```
|
||||||
|
|
||||||
|
### v3 color mode approach
|
||||||
|
|
||||||
|
Color mode is handled by `next-themes` via the generated `Provider`. Use
|
||||||
|
semantic tokens that automatically respond to the active color mode:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Use Chakra semantic tokens — they flip automatically in dark mode
|
||||||
|
<Box color="fg.default" bg="bg.subtle">
|
||||||
|
...
|
||||||
|
</Box>
|
||||||
|
```
|
||||||
|
|
||||||
|
For a color mode toggle, use the generated `components/ui/color-mode.tsx`
|
||||||
|
snippet or `useColorMode` from `next-themes` directly.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 6 — Prop renames
|
||||||
|
|
||||||
|
These boolean and style props were renamed in v3 for consistency with HTML and
|
||||||
|
modern React conventions. The codemod catches most of these, but verify manually
|
||||||
|
afterward.
|
||||||
|
|
||||||
|
### Boolean props
|
||||||
|
|
||||||
|
| v2 | v3 |
|
||||||
|
| ----------------- | --------------- |
|
||||||
|
| `isOpen` | `open` |
|
||||||
|
| `defaultIsOpen` | `defaultOpen` |
|
||||||
|
| `isDisabled` | `disabled` |
|
||||||
|
| `isInvalid` | `invalid` |
|
||||||
|
| `isRequired` | `required` |
|
||||||
|
| `isReadOnly` | `readOnly` |
|
||||||
|
| `isChecked` | `checked` |
|
||||||
|
| `isLoaded` | `loaded` |
|
||||||
|
| `isIndeterminate` | `indeterminate` |
|
||||||
|
|
||||||
|
### Style and layout props
|
||||||
|
|
||||||
|
| v2 | v3 |
|
||||||
|
| ----------------- | --------------------------- |
|
||||||
|
| `colorScheme` | `colorPalette` |
|
||||||
|
| `noOfLines` | `lineClamp` |
|
||||||
|
| `truncated` | `truncate` |
|
||||||
|
| `spacing` (Stack) | `gap` |
|
||||||
|
| `apply` | `textStyle` or `layerStyle` |
|
||||||
|
|
||||||
|
### Nested style props
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// v2 — sx with nested pseudo-selectors
|
||||||
|
<Box sx={{ "&:hover": { color: "blue.500" } }} />
|
||||||
|
|
||||||
|
// v3 — css prop with "&" selectors
|
||||||
|
<Box css={{ "&:hover": { color: "blue.500" } }} />
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 7 — Component migrations
|
||||||
|
|
||||||
|
### Renamed components
|
||||||
|
|
||||||
|
| v2 | v3 |
|
||||||
|
| ------------- | ----------------------------------- |
|
||||||
|
| `Modal` | `Dialog` |
|
||||||
|
| `FormControl` | `Field` |
|
||||||
|
| `Select` | `NativeSelect` |
|
||||||
|
| `AlertDialog` | `AlertDialog` (compound, see below) |
|
||||||
|
|
||||||
|
`Modal` is the most common rename — every `<Modal>`, `<ModalOverlay>`,
|
||||||
|
`<ModalContent>`, `<ModalHeader>`, `<ModalBody>`, `<ModalFooter>`, and
|
||||||
|
`<ModalCloseButton>` becomes a `Dialog.*` compound part:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// v2
|
||||||
|
<Modal isOpen={open} onClose={onClose}>
|
||||||
|
<ModalOverlay />
|
||||||
|
<ModalContent>
|
||||||
|
<ModalHeader>Title</ModalHeader>
|
||||||
|
<ModalBody>Body</ModalBody>
|
||||||
|
<ModalFooter><Button onClick={onClose}>Close</Button></ModalFooter>
|
||||||
|
</ModalContent>
|
||||||
|
</Modal>
|
||||||
|
|
||||||
|
// v3
|
||||||
|
<Dialog.Root open={open} onOpenChange={({ open }) => setOpen(open)}>
|
||||||
|
<Dialog.Backdrop />
|
||||||
|
<Dialog.Positioner>
|
||||||
|
<Dialog.Content>
|
||||||
|
<Dialog.Header><Dialog.Title>Title</Dialog.Title></Dialog.Header>
|
||||||
|
<Dialog.Body>Body</Dialog.Body>
|
||||||
|
<Dialog.Footer><Button onClick={() => setOpen(false)}>Close</Button></Dialog.Footer>
|
||||||
|
<Dialog.CloseTrigger />
|
||||||
|
</Dialog.Content>
|
||||||
|
</Dialog.Positioner>
|
||||||
|
</Dialog.Root>
|
||||||
|
```
|
||||||
|
|
||||||
|
### Compound component rewrites
|
||||||
|
|
||||||
|
v3 adopts a consistent compound component API. The codemod handles many of
|
||||||
|
these, but complex custom usage needs manual review.
|
||||||
|
|
||||||
|
**Checkbox**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// v2
|
||||||
|
<Checkbox isChecked={val} onChange={fn}>Label</Checkbox>
|
||||||
|
|
||||||
|
// v3
|
||||||
|
<Checkbox.Root checked={val} onCheckedChange={fn}>
|
||||||
|
<Checkbox.Control><Checkbox.Indicator /></Checkbox.Control>
|
||||||
|
<Checkbox.Label>Label</Checkbox.Label>
|
||||||
|
</Checkbox.Root>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Progress**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// v2
|
||||||
|
<Progress value={60} colorScheme="blue" />
|
||||||
|
|
||||||
|
// v3
|
||||||
|
<Progress.Root value={60} colorPalette="blue">
|
||||||
|
<Progress.Track><Progress.Range /></Progress.Track>
|
||||||
|
</Progress.Root>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Accordion**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// v2
|
||||||
|
<Accordion><AccordionItem><AccordionButton /><AccordionPanel /></AccordionItem></Accordion>
|
||||||
|
|
||||||
|
// v3
|
||||||
|
<Accordion.Root>
|
||||||
|
<Accordion.Item value="item-1">
|
||||||
|
<Accordion.ItemTrigger />
|
||||||
|
<Accordion.ItemContent />
|
||||||
|
</Accordion.Item>
|
||||||
|
</Accordion.Root>
|
||||||
|
```
|
||||||
|
|
||||||
|
**FormControl → Field**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// v2
|
||||||
|
<FormControl isInvalid={!!error} isRequired>
|
||||||
|
<FormLabel>Email</FormLabel>
|
||||||
|
<Input type="email" />
|
||||||
|
<FormErrorMessage>{error}</FormErrorMessage>
|
||||||
|
<FormHelperText>We'll never share your email.</FormHelperText>
|
||||||
|
</FormControl>
|
||||||
|
|
||||||
|
// v3
|
||||||
|
<Field.Root invalid={!!error} required>
|
||||||
|
<Field.Label>Email</Field.Label>
|
||||||
|
<Input type="email" />
|
||||||
|
<Field.ErrorText>{error}</Field.ErrorText>
|
||||||
|
<Field.HelpText>We'll never share your email.</Field.HelpText>
|
||||||
|
</Field.Root>
|
||||||
|
```
|
||||||
|
|
||||||
|
All `FormControl` sub-parts map to `Field.*`:
|
||||||
|
|
||||||
|
- `FormLabel` → `Field.Label`
|
||||||
|
- `FormErrorMessage` → `Field.ErrorText`
|
||||||
|
- `FormHelperText` → `Field.HelpText`
|
||||||
|
- `FormControl` props `isInvalid`, `isRequired`, `isDisabled` → `invalid`,
|
||||||
|
`required`, `disabled`
|
||||||
|
|
||||||
|
**Dialog / Drawer / Menu / Tabs** follow the same compound pattern: use
|
||||||
|
`ComponentName.Root`, `.Trigger`, `.Content`, `.Item`, etc. Check the Chakra UI
|
||||||
|
v3 docs for the specific compound API for each.
|
||||||
|
|
||||||
|
### Next.js Image and Link (replacing @chakra-ui/next-js)
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// v2 — @chakra-ui/next-js
|
||||||
|
import { LinkOverlay } from "@chakra-ui/next-js"
|
||||||
|
|
||||||
|
// v3 — asChild pattern
|
||||||
|
import NextLink from "next/link"
|
||||||
|
<ChakraLink asChild><NextLink href="/about">About</NextLink></ChakraLink>
|
||||||
|
|
||||||
|
import NextImage from "next/image"
|
||||||
|
<ChakraImage asChild><NextImage src="..." alt="..." /></ChakraImage>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 8 — Theming migration
|
||||||
|
|
||||||
|
### styleConfig and multiStyleConfig → recipes
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// v3 — single component (recipe)
|
||||||
|
import { defineRecipe } from "@chakra-ui/react"
|
||||||
|
|
||||||
|
// v2
|
||||||
|
const buttonStyle = {
|
||||||
|
baseStyle: { fontWeight: "bold" },
|
||||||
|
variants: { solid: { bg: "blue.500" } },
|
||||||
|
defaultProps: { variant: "solid" },
|
||||||
|
}
|
||||||
|
|
||||||
|
const buttonRecipe = defineRecipe({
|
||||||
|
base: { fontWeight: "bold" },
|
||||||
|
variants: { variant: { solid: { bg: "blue.500" } } },
|
||||||
|
defaultVariants: { variant: "solid" },
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// v3 — slot recipe
|
||||||
|
import { defineSlotRecipe } from "@chakra-ui/react"
|
||||||
|
|
||||||
|
// v2 — multiStyleConfig (multi-part component)
|
||||||
|
const cardStyle = multiStyleConfig({
|
||||||
|
parts: ["root", "header"],
|
||||||
|
baseStyle: { root: { bg: "white" }, header: { fontWeight: "bold" } },
|
||||||
|
})
|
||||||
|
|
||||||
|
const cardSlotRecipe = defineSlotRecipe({
|
||||||
|
slots: ["root", "header"],
|
||||||
|
base: { root: { bg: "white" }, header: { fontWeight: "bold" } },
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
### Typegen for custom tokens
|
||||||
|
|
||||||
|
After adding custom tokens, semantic tokens, recipes, or slot recipes, run
|
||||||
|
typegen to keep TypeScript types in sync:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx @chakra-ui/cli typegen ./theme.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
> **Complex theme migrations** — if you're moving a large v2 theme with many
|
||||||
|
> custom tokens, semantic tokens, or multi-part component styles, use the
|
||||||
|
> `chakra-ui-theming` skill. It covers the full token/recipe/slot-recipe API in
|
||||||
|
> depth and is a better guide than this section alone.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 9 — Next.js specifics
|
||||||
|
|
||||||
|
### App Router
|
||||||
|
|
||||||
|
- Place `<Provider>` in `app/layout.tsx` (Server Component — no `"use client"`)
|
||||||
|
- The generated `components/ui/provider.tsx` already has `"use client"`
|
||||||
|
- Add `suppressHydrationWarning` to `<html>` to prevent color mode flicker
|
||||||
|
- Do not wrap the entire app or layout in `"use client"`
|
||||||
|
|
||||||
|
### Pages Router
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// pages/_app.js
|
||||||
|
import { Provider } from "@/components/ui/provider"
|
||||||
|
|
||||||
|
export default function App({ Component, pageProps }) {
|
||||||
|
return (
|
||||||
|
<Provider>
|
||||||
|
<Component {...pageProps} />
|
||||||
|
</Provider>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Remove any `ColorModeScript` from `pages/_document.tsx` — it is not used in v3.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 10 — Validation checklist
|
||||||
|
|
||||||
|
Work through this after the migration is complete:
|
||||||
|
|
||||||
|
- [ ] Reinstall dependencies: `npm install` / `pnpm install`
|
||||||
|
- [ ] TypeScript: `npx tsc --noEmit` — resolve all type errors
|
||||||
|
- [ ] Lint: `npm run lint`
|
||||||
|
- [ ] Build: `npm run build`
|
||||||
|
- [ ] Visually verify color mode toggle (light ↔ dark)
|
||||||
|
- [ ] Test interactive components: Dialog, Drawer, Menu, Tabs, Accordion
|
||||||
|
- [ ] Test form components: Checkbox, Select/NativeSelect, Input, Radio
|
||||||
|
- [ ] Check for visual regressions across key pages
|
||||||
|
- [ ] Search codebase for leftover v2 imports:
|
||||||
|
```bash
|
||||||
|
grep -r "ColorModeScript\|useColorModeValue\|extendTheme\|styleConfig\|@chakra-ui/icons\|@chakra-ui/next-js" src/
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Clarifying questions (when context is unclear)
|
||||||
|
|
||||||
|
If the user's version, framework, or scope is ambiguous, ask:
|
||||||
|
|
||||||
|
1. "What version of `@chakra-ui/react` are you on right now?"
|
||||||
|
2. "Are you using Next.js App Router, Pages Router, Vite, or plain React?"
|
||||||
|
3. "Are you migrating the full codebase or just specific components?"
|
||||||
|
|
||||||
|
State assumptions clearly if you proceed without asking.
|
||||||
@@ -0,0 +1,284 @@
|
|||||||
|
---
|
||||||
|
name: chakra-ui-refactor
|
||||||
|
description: >
|
||||||
|
Review, convert, and improve UI code using Chakra UI v3. Use this skill
|
||||||
|
whenever a user wants to review Chakra UI code for issues, convert plain
|
||||||
|
HTML/CSS, Tailwind, CSS Modules, or styled-components to Chakra UI, clean up
|
||||||
|
messy Chakra components, fix layout structure or token usage, or asks anything
|
||||||
|
like "is this correct", "what's wrong with this", "review my component",
|
||||||
|
"refactor this", "clean up", "convert", or "chakra-ify this" — even without
|
||||||
|
the words "review" or "refactor". Trigger on any request to check, improve, or
|
||||||
|
convert Chakra UI code, however casually phrased.
|
||||||
|
---
|
||||||
|
|
||||||
|
# Chakra UI Refactor & Review
|
||||||
|
|
||||||
|
You are reviewing and improving UI code using Chakra UI v3. Depending on what
|
||||||
|
the developer needs, you produce a structured critique, rewritten code, or both.
|
||||||
|
Read the code and project context fully before producing any output.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 1 — Orient and determine intent
|
||||||
|
|
||||||
|
Before any output, establish:
|
||||||
|
|
||||||
|
- **Chakra UI version** — check `package.json`; use v3 by default
|
||||||
|
- **Framework** — Next.js App Router, Pages Router, Vite, plain React
|
||||||
|
- **Source type** — existing Chakra, plain HTML/CSS, Tailwind, CSS Modules,
|
||||||
|
styled-components
|
||||||
|
- **What the user is asking:**
|
||||||
|
- **Review only** — "check this", "is this correct/idiomatic", "what's wrong",
|
||||||
|
"review my code" → produce a critique with targeted fixes, no full rewrite
|
||||||
|
- **Refactor / convert** — "refactor this", "convert from Tailwind", "clean
|
||||||
|
this up" → produce rewritten code
|
||||||
|
- **Both** — "review and fix" → critique first, then the rewritten code
|
||||||
|
|
||||||
|
State your reading at the top of the response (e.g. "Reviewing as existing
|
||||||
|
Chakra v3 code. Assuming Next.js App Router.").
|
||||||
|
|
||||||
|
If code isn't shared yet, ask for it. Don't review a description of code.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 2 — Analyze the code
|
||||||
|
|
||||||
|
Work through the code across these dimensions regardless of output mode. For
|
||||||
|
review, they become findings. For refactor, they become the checklist of what to
|
||||||
|
fix.
|
||||||
|
|
||||||
|
**Accessibility**
|
||||||
|
|
||||||
|
- Do all interactive elements have accessible labels? (`aria-label` on icon
|
||||||
|
buttons, `htmlFor`/`id` on label+input pairs, `alt` on images)
|
||||||
|
- Is keyboard navigation possible? (focus rings not suppressed, interactive
|
||||||
|
elements are actually focusable)
|
||||||
|
- Does the heading hierarchy make sense? (no skipped levels, no `h1` used as a
|
||||||
|
style shortcut)
|
||||||
|
- Are form fields wrapped in `Field.Root` with `Field.Label` and
|
||||||
|
`Field.ErrorText`?
|
||||||
|
- Does the component work without color as the only signal?
|
||||||
|
|
||||||
|
**Responsiveness**
|
||||||
|
|
||||||
|
- Do layout components specify behavior at multiple breakpoints?
|
||||||
|
- Are there hardcoded pixel values where responsive tokens would work better?
|
||||||
|
- Would this break on mobile? (fixed widths, `overflow: hidden` on small
|
||||||
|
viewports)
|
||||||
|
|
||||||
|
**Chakra API correctness**
|
||||||
|
|
||||||
|
- Are v3 prop names used? (`disabled` not `isDisabled`, `colorPalette` not
|
||||||
|
`colorScheme`, `gap` not `spacing`, `open` not `isOpen`)
|
||||||
|
- Are compound components used correctly? (`Field.Root`/`Field.Label`,
|
||||||
|
`Dialog.Root`/`Dialog.Content`, etc.)
|
||||||
|
- Is `"use client"` placed correctly in Next.js App Router?
|
||||||
|
- Are there v2 patterns still present? (`extendTheme`, `ColorModeScript`,
|
||||||
|
`useColorModeValue`, `sx` prop)
|
||||||
|
|
||||||
|
**Token and style usage**
|
||||||
|
|
||||||
|
- Are hardcoded colors used where semantic tokens would work? (`bg="#f9fafb"` →
|
||||||
|
`bg="bg.subtle"`)
|
||||||
|
- Are raw hex or palette values used instead of semantic tokens? These won't
|
||||||
|
respect dark mode.
|
||||||
|
- Are there inline `style={{}}` props that should be Chakra style props?
|
||||||
|
|
||||||
|
**Component structure**
|
||||||
|
|
||||||
|
- Is there unnecessary nesting? (`Box > Box > Box` when one would do)
|
||||||
|
- Is manual spacing (`mt={4}` on every child) used where `Stack gap={4}` would
|
||||||
|
be cleaner?
|
||||||
|
- Are the right layout primitives used? (`Flex` vs `Stack` vs `Grid` vs
|
||||||
|
`SimpleGrid`)
|
||||||
|
|
||||||
|
**Maintainability**
|
||||||
|
|
||||||
|
- Does the same visual pattern repeat 3+ times? (candidate for a component or
|
||||||
|
recipe)
|
||||||
|
- Are there one-off style overrides that suggest a recipe or slot recipe?
|
||||||
|
- Are prop types / TypeScript types present and accurate?
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 3a — Review output
|
||||||
|
|
||||||
|
Use this when the user wants a critique, not a rewrite.
|
||||||
|
|
||||||
|
Categorize findings by impact:
|
||||||
|
|
||||||
|
**Critical** — bugs and accessibility failures that break behavior or exclude
|
||||||
|
users
|
||||||
|
|
||||||
|
- Missing `aria-label` on an icon-only button
|
||||||
|
- Form field with no label association
|
||||||
|
- Interactive `Box` with `onClick` but no keyboard access
|
||||||
|
- Wrong v3 prop name that silently does nothing (`isDisabled` doesn't disable in
|
||||||
|
v3)
|
||||||
|
- `"use client"` missing on a component that uses hooks in App Router
|
||||||
|
|
||||||
|
**Improvements** — correctness and quality issues that aren't urgent
|
||||||
|
|
||||||
|
- Hardcoded colors that break dark mode
|
||||||
|
- Missing responsive breakpoints
|
||||||
|
- Unnecessary nesting or wrong layout primitive
|
||||||
|
- v2 patterns that still work but should be updated
|
||||||
|
|
||||||
|
**Optional suggestions** — non-blocking ideas
|
||||||
|
|
||||||
|
- Extract a repeated pattern into a component
|
||||||
|
- Replace a one-off style with a recipe variant
|
||||||
|
- Add a missing TypeScript type
|
||||||
|
|
||||||
|
For each critical issue and significant improvement, show a minimal fix:
|
||||||
|
|
||||||
|
```
|
||||||
|
**Missing aria-label on close button** (Critical)
|
||||||
|
The IconButton for closing the dialog has no accessible label.
|
||||||
|
|
||||||
|
// Before
|
||||||
|
<IconButton icon={<CloseIcon />} onClick={onClose} />
|
||||||
|
// After
|
||||||
|
<IconButton aria-label="Close dialog" icon={<CloseIcon />} onClick={onClose} />
|
||||||
|
```
|
||||||
|
|
||||||
|
Skip sections with nothing to report. Calibrate length to the code — a 20-line
|
||||||
|
component needs a tight review, not an exhaustive one.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 3b — Refactor / convert output
|
||||||
|
|
||||||
|
Use this when the user wants rewritten code.
|
||||||
|
|
||||||
|
### Conversion strategy by source
|
||||||
|
|
||||||
|
**From plain HTML / CSS**
|
||||||
|
|
||||||
|
| HTML | Chakra equivalent |
|
||||||
|
| ------------------------ | ------------------------------------------- |
|
||||||
|
| `<div>` layout wrapper | `Box`, `Flex`, `Stack`, `Grid` |
|
||||||
|
| `<section>`, `<article>` | `Box as="section"`, `Box as="article"` |
|
||||||
|
| `<nav>` | `Box as="nav"` |
|
||||||
|
| `<ul>` / `<li>` | `Box as="ul"` / `Box as="li"`, or `Stack` |
|
||||||
|
| `<button>` | `Button` or `IconButton` |
|
||||||
|
| `<a>` | `Link` |
|
||||||
|
| `<img>` | `Image` (preserve `alt`) |
|
||||||
|
| `<input>`, `<select>` | `Input`, `NativeSelect` inside `Field.Root` |
|
||||||
|
|
||||||
|
| CSS | Chakra style prop |
|
||||||
|
| ------------------------ | ----------------------------- |
|
||||||
|
| `display: flex` | `Flex` or `display="flex"` |
|
||||||
|
| `flex-direction: column` | `Stack` or `flexDir="column"` |
|
||||||
|
| `gap: 16px` | `gap={4}` (1 unit = 4px) |
|
||||||
|
| `padding: 16px 24px` | `py={4} px={6}` |
|
||||||
|
| `border-radius: 8px` | `rounded="md"` |
|
||||||
|
| `color: #6b7280` | `color="fg.muted"` |
|
||||||
|
| `background: #f9fafb` | `bg="bg.subtle"` |
|
||||||
|
|
||||||
|
**From Tailwind CSS**
|
||||||
|
|
||||||
|
| Tailwind | Chakra |
|
||||||
|
| ------------------------------ | ---------------------------------------- |
|
||||||
|
| `flex`, `flex-col`, `flex-row` | `Flex`, `flexDir` |
|
||||||
|
| `gap-4` | `gap={4}` |
|
||||||
|
| `p-4`, `px-6`, `py-2` | `p={4}`, `px={6}`, `py={2}` |
|
||||||
|
| `text-sm`, `font-bold` | `fontSize="sm"`, `fontWeight="bold"` |
|
||||||
|
| `rounded-lg`, `shadow-md` | `rounded="lg"`, `shadow="md"` |
|
||||||
|
| `w-full`, `max-w-lg` | `w="full"`, `maxW="lg"` |
|
||||||
|
| `hidden md:flex` | `display={{ base: "none", md: "flex" }}` |
|
||||||
|
| `grid grid-cols-3` | `SimpleGrid columns={3}` |
|
||||||
|
| `text-gray-500`, `bg-gray-100` | `color="fg.muted"`, `bg="bg.subtle"` |
|
||||||
|
| `hover:bg-gray-100` | `_hover={{ bg: "bg.subtle" }}` |
|
||||||
|
|
||||||
|
Replace Tailwind responsive prefixes with Chakra's breakpoint object syntax:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Tailwind: text-sm md:base lg:text-lg
|
||||||
|
<Text fontSize={{ base: "sm", md: "md", lg: "lg" }} />
|
||||||
|
```
|
||||||
|
|
||||||
|
**From CSS Modules** — convert what you can to Chakra props; keep `className`
|
||||||
|
for styles that can't be expressed as props (animations, complex selectors):
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Before
|
||||||
|
<div className={styles.card}>...</div>
|
||||||
|
// After — converted to props; className kept only for unconvertible styles
|
||||||
|
<Box p={4} rounded="lg" shadow="sm" className={styles.fadeIn}>...</Box>
|
||||||
|
```
|
||||||
|
|
||||||
|
Once all class names are eliminated, remove the import entirely.
|
||||||
|
|
||||||
|
**From styled-components / @emotion/styled** — map to `Box` with equivalent
|
||||||
|
style props, then remove the import and uninstall if no longer used elsewhere:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Before
|
||||||
|
const Card = styled.div`padding: 1rem; &:hover { background: #f3f4f6; }`
|
||||||
|
// After
|
||||||
|
<Box p={4} _hover={{ bg: "bg.muted" }} />
|
||||||
|
```
|
||||||
|
|
||||||
|
**From existing Chakra UI (cleanup)**
|
||||||
|
|
||||||
|
- Flatten `Box > Box > Box` nesting; replace `mt`/`mb` on every child with
|
||||||
|
`Stack gap={N}`
|
||||||
|
- Replace `sx` with `css` (v3 rename); update nested `&:hover` selectors inside
|
||||||
|
it
|
||||||
|
- Replace `bg="gray.50"` → `bg="bg.subtle"` and other semantic token equivalents
|
||||||
|
- Update v2 prop names: `isDisabled→disabled`, `colorScheme→colorPalette`,
|
||||||
|
`spacing→gap`
|
||||||
|
- Update compound components: `FormControl→Field.Root`, `Modal→Dialog`,
|
||||||
|
`Select→NativeSelect`
|
||||||
|
|
||||||
|
### Preserve behavior — non-negotiable
|
||||||
|
|
||||||
|
- Keep all event handlers, state variables, and conditional rendering exactly
|
||||||
|
as-is
|
||||||
|
- Keep `aria-*` attributes; add missing ones where clearly needed
|
||||||
|
- Keep semantic HTML intent (`<nav>` → `Box as="nav"`, not just `Box`)
|
||||||
|
- Keep `"use client"` where it exists; add it only when the component genuinely
|
||||||
|
needs it
|
||||||
|
- Don't add `"use client"` just because a component uses Chakra UI
|
||||||
|
- A partially-converted component that works is better than a fully-converted
|
||||||
|
one that doesn't
|
||||||
|
|
||||||
|
### `asChild` for Next.js Link and Image
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import NextLink from "next/link"
|
||||||
|
<ChakraLink asChild><NextLink href="/about">About</NextLink></ChakraLink>
|
||||||
|
|
||||||
|
import NextImage from "next/image"
|
||||||
|
<ChakraImage asChild><NextImage src="/hero.png" alt="Hero" width={800} height={400} /></ChakraImage>
|
||||||
|
```
|
||||||
|
|
||||||
|
### Refactor output format
|
||||||
|
|
||||||
|
**1. Refactored code** — complete, runnable, with correct imports
|
||||||
|
|
||||||
|
**2. What changed** — concise list focused on non-obvious decisions:
|
||||||
|
|
||||||
|
```
|
||||||
|
- Replaced <div className="flex gap-4"> with <Flex gap={4}>
|
||||||
|
- Replaced bg="#f9fafb" with bg="bg.subtle" for dark mode compatibility
|
||||||
|
- Kept form submit handler and validation logic unchanged
|
||||||
|
- Added aria-label to close icon button (was missing)
|
||||||
|
```
|
||||||
|
|
||||||
|
**3. Suggestions** (optional) — meaningful improvements beyond this refactor:
|
||||||
|
extracting a reusable component, adopting a recipe, migrating a v2 pattern.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## When to ask vs proceed
|
||||||
|
|
||||||
|
Proceed if the code and intent are clear. Ask when:
|
||||||
|
|
||||||
|
- The code isn't shared yet
|
||||||
|
- The component is very large and scope is unclear
|
||||||
|
- There's context or state you can't see that would change the review
|
||||||
|
- There's ambiguous behavior that could be interpreted multiple ways
|
||||||
|
|
||||||
|
State assumptions at the top of the response when you proceed without asking.
|
||||||
@@ -0,0 +1,374 @@
|
|||||||
|
---
|
||||||
|
name: chakra-ui-builder
|
||||||
|
description: >
|
||||||
|
Build responsive, accessible UI components and layouts using Chakra UI v3,
|
||||||
|
install or configure Chakra UI in new and existing projects, and design
|
||||||
|
scalable themes using tokens, semantic tokens, recipes, and slot recipes. Use
|
||||||
|
this skill whenever a user asks to build, create, or generate any UI
|
||||||
|
component, page, form, dashboard, navbar, card, landing section, pricing
|
||||||
|
table, or layout using Chakra UI; wants to add Chakra UI to a project, set up
|
||||||
|
ChakraProvider, run CLI snippets, configure color mode, or fix provider
|
||||||
|
wrapping; or asks about theming — defining brand colors, design tokens,
|
||||||
|
semantic tokens, dark mode values, component recipes, slot recipes, typegen,
|
||||||
|
or ejecting the default theme. Trigger on any Chakra UI building, setup, or
|
||||||
|
theming or charts request, however casually phrased — "add my brand colors",
|
||||||
|
"make a reusable card style", "build a bar chart", "show me a line chart",
|
||||||
|
"make me a login form", "build a sidebar", "add Chakra to my app".
|
||||||
|
---
|
||||||
|
|
||||||
|
# Chakra UI Builder
|
||||||
|
|
||||||
|
You are building UI with Chakra UI v3 and helping developers set up Chakra UI in
|
||||||
|
their projects. Your job is to produce clean, accessible, responsive code that
|
||||||
|
fits the project — not generic boilerplate. Read the project context first, then
|
||||||
|
build or set up.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 1 — Read the project context
|
||||||
|
|
||||||
|
Check `package.json` if available. Look for:
|
||||||
|
|
||||||
|
- Chakra UI version (use v3 patterns by default; only use v2 if explicitly on
|
||||||
|
v2)
|
||||||
|
- Framework: Next.js App Router, Pages Router, Vite, plain React
|
||||||
|
- TypeScript or JavaScript
|
||||||
|
- Package manager (from lockfile: `pnpm-lock.yaml`, `yarn.lock`, `bun.lock`,
|
||||||
|
`package-lock.json`)
|
||||||
|
|
||||||
|
Also glance at existing components if the user references them, so your code
|
||||||
|
matches the conventions already in use (naming, file structure, import style).
|
||||||
|
|
||||||
|
If the requirements are vague or the component is complex enough that choices
|
||||||
|
matter (layout direction, data shape, color palette, number of variants), ask
|
||||||
|
before building rather than generating something that needs to be thrown away.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Project setup
|
||||||
|
|
||||||
|
If Chakra UI isn't installed yet, complete setup before building.
|
||||||
|
|
||||||
|
### Install
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# npm
|
||||||
|
npm install @chakra-ui/react @emotion/react
|
||||||
|
|
||||||
|
# pnpm
|
||||||
|
pnpm add @chakra-ui/react @emotion/react
|
||||||
|
|
||||||
|
# yarn
|
||||||
|
yarn add @chakra-ui/react @emotion/react
|
||||||
|
|
||||||
|
# bun
|
||||||
|
bun add @chakra-ui/react @emotion/react
|
||||||
|
```
|
||||||
|
|
||||||
|
### Generate snippets with the CLI
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx @chakra-ui/cli snippet add
|
||||||
|
```
|
||||||
|
|
||||||
|
With no arguments this adds the recommended set — `provider`, `toaster`, and
|
||||||
|
`tooltip` — and automatically installs required dependencies (including
|
||||||
|
`next-themes`). Use `--all` to add every snippet, or `snippet list` to browse
|
||||||
|
first.
|
||||||
|
|
||||||
|
The CLI detects your framework and writes files to the right place:
|
||||||
|
|
||||||
|
| Framework | Output path |
|
||||||
|
| --------------------- | -------------------- |
|
||||||
|
| Next.js (with `src/`) | `src/components/ui/` |
|
||||||
|
| Next.js (no `src/`) | `components/ui/` |
|
||||||
|
| Vite / plain React | `src/components/ui/` |
|
||||||
|
| Remix | `app/components/ui/` |
|
||||||
|
|
||||||
|
### Wire up the Provider
|
||||||
|
|
||||||
|
**Next.js App Router** (`app/layout.tsx`):
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { Provider } from "@/components/ui/provider"
|
||||||
|
|
||||||
|
export default function RootLayout({
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
children: React.ReactNode
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<html lang="en" suppressHydrationWarning>
|
||||||
|
<body>
|
||||||
|
<Provider>{children}</Provider>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`suppressHydrationWarning` prevents a mismatch caused by `next-themes` injecting
|
||||||
|
the color-mode class. Do **not** add `"use client"` to `layout.tsx` — the
|
||||||
|
generated provider file already has it.
|
||||||
|
|
||||||
|
**Next.js Pages Router** (`pages/_app.tsx`):
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { Provider } from "@/components/ui/provider"
|
||||||
|
|
||||||
|
export default function App({ Component, pageProps }) {
|
||||||
|
return (
|
||||||
|
<Provider>
|
||||||
|
<Component {...pageProps} />
|
||||||
|
</Provider>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Vite** (`src/main.tsx`):
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { Provider } from "./components/ui/provider"
|
||||||
|
|
||||||
|
createRoot(document.getElementById("root")!).render(
|
||||||
|
<StrictMode>
|
||||||
|
<Provider>
|
||||||
|
<App />
|
||||||
|
</Provider>
|
||||||
|
</StrictMode>,
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Manual Provider (if CLI is unavailable)
|
||||||
|
|
||||||
|
If the CLI fails, create `components/ui/provider.tsx` manually and install
|
||||||
|
`next-themes` separately:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
"use client"
|
||||||
|
import { ChakraProvider, defaultSystem } from "@chakra-ui/react"
|
||||||
|
import { ThemeProvider } from "next-themes"
|
||||||
|
|
||||||
|
export function Provider({ children }: { children: React.ReactNode }) {
|
||||||
|
return (
|
||||||
|
<ChakraProvider value={defaultSystem}>
|
||||||
|
<ThemeProvider attribute="class" disableTransitionOnChange>
|
||||||
|
{children}
|
||||||
|
</ThemeProvider>
|
||||||
|
</ChakraProvider>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Common setup issues
|
||||||
|
|
||||||
|
- **Unstyled components** — app is not wrapped in `<Provider>`. Check the import
|
||||||
|
path and that `Provider` wraps the component tree.
|
||||||
|
- **Hydration mismatch** — add `suppressHydrationWarning` to `<html>` in App
|
||||||
|
Router.
|
||||||
|
- **`next-themes` not found** — install it: `npm install next-themes` (only
|
||||||
|
needed for the manual fallback; the CLI handles it automatically).
|
||||||
|
- **`extendTheme` not exported** — this is a v2 pattern. Use `createSystem` in
|
||||||
|
v3.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 2 — Choose the right layout primitives
|
||||||
|
|
||||||
|
Reach for the right Chakra primitive rather than wrapping everything in `Box`:
|
||||||
|
|
||||||
|
| Need | Use |
|
||||||
|
| ------------------------ | --------------------------------------- |
|
||||||
|
| Vertical stack of items | `Stack` (default) or `VStack` |
|
||||||
|
| Horizontal row | `HStack` or `Flex` |
|
||||||
|
| CSS Grid | `Grid` + `GridItem` |
|
||||||
|
| Equal-column grid | `SimpleGrid columns={N}` |
|
||||||
|
| Centered page content | `Container maxW="container.lg"` |
|
||||||
|
| Full flexbox control | `Flex` with explicit props |
|
||||||
|
| Semantic section/article | `Box as="section"` / `Box as="article"` |
|
||||||
|
|
||||||
|
Avoid deep nesting. If you're three `Box` levels deep with no semantic reason,
|
||||||
|
flatten it. Prefer `gap` over margin between siblings.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 3 — Use tokens, not raw values
|
||||||
|
|
||||||
|
Chakra v3 ships semantic tokens that automatically adapt to light/dark mode.
|
||||||
|
Prefer them over hard-coded palette values — they make the component theme-aware
|
||||||
|
without any extra work.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Prefer semantic tokens
|
||||||
|
<Box bg="bg.subtle" color="fg.default" borderColor="border.subtle" />
|
||||||
|
<Text color="fg.muted" />
|
||||||
|
<Box shadow="md" rounded="lg" />
|
||||||
|
|
||||||
|
// Use colorPalette for interactive components (not colorScheme)
|
||||||
|
<Button colorPalette="blue">Submit</Button>
|
||||||
|
<Badge colorPalette="green">Active</Badge>
|
||||||
|
```
|
||||||
|
|
||||||
|
Use raw palette values (`blue.500`, `gray.100`) only when a specific color is
|
||||||
|
intentional and should not shift with color mode.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 4 — Responsive styles
|
||||||
|
|
||||||
|
Chakra uses mobile-first breakpoints. Use array or object syntax consistently:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Array: [base, sm, md, lg, xl]
|
||||||
|
<Box px={[4, 6, 8]} fontSize={["sm", "md", "lg"]} />
|
||||||
|
|
||||||
|
// Object: explicit breakpoints
|
||||||
|
<SimpleGrid columns={{ base: 1, md: 2, lg: 3 }} gap={6} />
|
||||||
|
<Stack direction={{ base: "column", md: "row" }} gap={4} />
|
||||||
|
```
|
||||||
|
|
||||||
|
Every layout component should handle at least `base` (mobile) and `md` (desktop)
|
||||||
|
breakpoints unless the request is explicitly desktop-only.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 5 — Forms
|
||||||
|
|
||||||
|
Use `Field.Root` for all form fields — it wires up label, input, error, and help
|
||||||
|
text correctly:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Field.Root invalid={!!error} required>
|
||||||
|
<Field.Label>Email address</Field.Label>
|
||||||
|
<Input type="email" placeholder="you@example.com" />
|
||||||
|
<Field.ErrorText>{error}</Field.ErrorText>
|
||||||
|
<Field.HelpText>We'll never share your email.</Field.HelpText>
|
||||||
|
</Field.Root>
|
||||||
|
```
|
||||||
|
|
||||||
|
For form submission state, use `disabled` (not `isDisabled`) on inputs and
|
||||||
|
buttons. Group related fields in a `Stack gap={4}`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 6 — Accessibility
|
||||||
|
|
||||||
|
Chakra's built-in components handle most accessibility automatically — don't
|
||||||
|
override it. The things you do need to provide:
|
||||||
|
|
||||||
|
- **Icon-only buttons**: always add `aria-label`
|
||||||
|
```tsx
|
||||||
|
<IconButton aria-label="Close dialog" icon={<CloseIcon />} />
|
||||||
|
```
|
||||||
|
- **Images**: always pass meaningful `alt` text (or `alt=""` for decorative)
|
||||||
|
- **Form labels**: use `Field.Label` or ensure `htmlFor` matches the input `id`
|
||||||
|
- **Interactive custom elements**: if you build something with `onClick` on a
|
||||||
|
`Box`, use `as="button"` or an actual `<button>` so keyboard navigation works
|
||||||
|
- **Semantic headings**: use `h1`–`h6` hierarchy; don't skip levels
|
||||||
|
- **Color contrast**: don't use light gray text on white backgrounds; rely on
|
||||||
|
semantic tokens which are contrast-tested
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 7 — Next.js: where to add `"use client"`
|
||||||
|
|
||||||
|
In Next.js App Router, Server Components are the default. Add `"use client"`
|
||||||
|
only to files that need it — not to entire layouts or pages.
|
||||||
|
|
||||||
|
A component needs `"use client"` when it:
|
||||||
|
|
||||||
|
- Uses React hooks (`useState`, `useEffect`, `useContext`, etc.)
|
||||||
|
- Handles browser events (`onClick` with state, form submission, etc.)
|
||||||
|
- Uses browser APIs
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Server Component — no directive needed
|
||||||
|
export default function ProductCard({ name, price }: Props) {
|
||||||
|
return (
|
||||||
|
<Box p={4} borderWidth={1} rounded="md">
|
||||||
|
<Text fontWeight="bold">{name}</Text>
|
||||||
|
<Text color="fg.muted">{price}</Text>
|
||||||
|
</Box>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Client Component — needs the directive
|
||||||
|
;("use client")
|
||||||
|
export function AddToCartButton({ productId }: { productId: string }) {
|
||||||
|
const [added, setAdded] = useState(false)
|
||||||
|
return (
|
||||||
|
<Button onClick={() => setAdded(true)} colorPalette="blue">
|
||||||
|
{added ? "Added!" : "Add to cart"}
|
||||||
|
</Button>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The goal is to push interactivity to the leaves — keep as much of the tree as
|
||||||
|
Server Components as possible.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 8 — When to extract components, use recipes, and customize the theme
|
||||||
|
|
||||||
|
Extract a component when the same structure appears more than twice, or when a
|
||||||
|
piece is complex enough that naming it makes the parent clearer.
|
||||||
|
|
||||||
|
Suggest a **recipe** when a component has meaningful style variants that a
|
||||||
|
developer would want to customize. Suggest a **slot recipe** for components with
|
||||||
|
multiple coordinated parts (card with header/body/footer, stat with
|
||||||
|
label/value/icon, etc.).
|
||||||
|
|
||||||
|
For deeper theming work — defining brand color tokens, semantic tokens with dark
|
||||||
|
mode values, full recipe/slot-recipe authoring, typegen, or ejecting the default
|
||||||
|
theme — read `references/theming.md` before responding. It covers the complete
|
||||||
|
`defineConfig` / `createSystem` API with full examples.
|
||||||
|
|
||||||
|
For any chart request — bar charts, area charts, line charts, pie/donut charts,
|
||||||
|
`BarList`, `BarSegment`, or anything involving `@chakra-ui/charts` — read
|
||||||
|
`references/charts.md` before responding. It covers the `useChart` hook, all
|
||||||
|
three chart types, Recharts integration, color tokens, and complete runnable
|
||||||
|
examples.
|
||||||
|
|
||||||
|
When you're unsure which component to use, or the user hasn't specified one,
|
||||||
|
read `references/component-decision-tree.md`. It covers every Chakra component
|
||||||
|
with guidance on when to choose one over a similar alternative.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Output format
|
||||||
|
|
||||||
|
Produce:
|
||||||
|
|
||||||
|
1. **Complete, runnable code** — correct imports, no placeholders like `TODO` or
|
||||||
|
`...rest of component`
|
||||||
|
2. **Proper import statements** — group Chakra imports, then local imports
|
||||||
|
3. **Component separation** — split into multiple components/files if the
|
||||||
|
component is complex or contains clearly separable parts
|
||||||
|
4. **Responsive styles** — at minimum `base` and `md` breakpoints for layout
|
||||||
|
5. **Brief explanation after the code** — 2–4 sentences on the key decisions
|
||||||
|
made (layout approach, accessibility choices, responsive strategy). Skip the
|
||||||
|
explanation if the request was trivial.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Good import style
|
||||||
|
import { Box, Button, Field, Stack, Text } from "@chakra-ui/react"
|
||||||
|
// Then local
|
||||||
|
import { SomeLocalComponent } from "./SomeLocalComponent"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## When to ask first
|
||||||
|
|
||||||
|
Build immediately if the request is clear enough to produce something useful.
|
||||||
|
Ask first when:
|
||||||
|
|
||||||
|
- The data shape is unknown and it changes the entire structure (e.g., "build a
|
||||||
|
table" — how many columns? what data?)
|
||||||
|
- There are meaningful design choices the user might care about (layout
|
||||||
|
direction, number of columns, color palette)
|
||||||
|
- The user references files or existing components you haven't seen
|
||||||
|
|
||||||
|
When in doubt, state your assumptions at the top of the response and build —
|
||||||
|
it's faster for the user to redirect from something concrete than from nothing.
|
||||||
@@ -0,0 +1,461 @@
|
|||||||
|
# Chakra UI Charts Reference
|
||||||
|
|
||||||
|
Charts live in a separate package. Install it alongside `@chakra-ui/react`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# npm
|
||||||
|
npm install @chakra-ui/charts recharts
|
||||||
|
|
||||||
|
# pnpm
|
||||||
|
pnpm add @chakra-ui/charts recharts
|
||||||
|
|
||||||
|
# yarn
|
||||||
|
yarn add @chakra-ui/charts recharts
|
||||||
|
```
|
||||||
|
|
||||||
|
Imports come from `@chakra-ui/charts`, not `@chakra-ui/react`:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { BarList, BarSegment, Chart, useChart } from "@chakra-ui/charts"
|
||||||
|
import type { BarListData, BarSegmentData } from "@chakra-ui/charts"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Three chart types
|
||||||
|
|
||||||
|
| Component | Best for | Recharts? |
|
||||||
|
| ----------------------- | ---------------------------------------------- | --------- |
|
||||||
|
| `BarList` | Rankings, comparisons (horizontal bar per row) | No |
|
||||||
|
| `BarSegment` | Composition / parts of a whole (stacked bar) | No |
|
||||||
|
| `Chart.Root` + Recharts | Line, area, bar, pie, radar, and more | Yes |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## `useChart` — the core hook
|
||||||
|
|
||||||
|
Every chart starts with `useChart`. It processes data, resolves color tokens,
|
||||||
|
and provides utilities used throughout the chart's compound components.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
const chart = useChart({
|
||||||
|
data: [...], // array of data objects
|
||||||
|
series: [...], // which keys to plot and how to color them
|
||||||
|
sort: { by: "value", direction: "desc" }, // optional
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
**`series` items:**
|
||||||
|
|
||||||
|
```ts
|
||||||
|
{
|
||||||
|
name: keyof T // data key to read values from
|
||||||
|
color: ChartColor // Chakra token ("teal.solid") or CSS color ("#FF0000")
|
||||||
|
label?: ReactNode // display name in legend/tooltip (defaults to name)
|
||||||
|
stackId?: string // for stacking in Recharts charts
|
||||||
|
yAxisId?: string // for dual-axis charts
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Color type** — accepts any Chakra color token or CSS color:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
type ChartColor = Tokens["colors"] | CSSProperties["color"]
|
||||||
|
// "teal.solid" | "blue.subtle" | "red.500" | "#FF0000" | "hsl(...)"
|
||||||
|
```
|
||||||
|
|
||||||
|
**Useful return values:**
|
||||||
|
|
||||||
|
```ts
|
||||||
|
chart.data // sorted data array
|
||||||
|
chart.series // resolved series config
|
||||||
|
chart.color("teal.solid") // resolves token → CSS color
|
||||||
|
chart.key("revenue") // safe key accessor
|
||||||
|
chart.formatNumber({ notation: "compact" })(1234567) // "1.2M"
|
||||||
|
chart.formatDate({ month: "short" })("2024-01-15") // locale-aware
|
||||||
|
chart.getTotal("revenue") // sum all values
|
||||||
|
chart.getMin("revenue") / chart.getMax("revenue")
|
||||||
|
chart.getValuePercent("revenue", value) // % of total
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## BarList
|
||||||
|
|
||||||
|
Horizontal bar chart — one bar per data row. Good for leaderboards, traffic
|
||||||
|
sources, top items.
|
||||||
|
|
||||||
|
**Data shape:**
|
||||||
|
|
||||||
|
```ts
|
||||||
|
interface BarListData {
|
||||||
|
name: string // label shown on the bar
|
||||||
|
value: number // determines bar width
|
||||||
|
href?: string // optional link
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Basic example:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { BarList, type BarListData, useChart } from "@chakra-ui/charts"
|
||||||
|
|
||||||
|
const chart = useChart<BarListData>({
|
||||||
|
data: [
|
||||||
|
{ name: "Google", value: 1_200_000 },
|
||||||
|
{ name: "Direct", value: 840_000 },
|
||||||
|
{ name: "Twitter", value: 320_000 },
|
||||||
|
{ name: "LinkedIn", value: 95_000 },
|
||||||
|
],
|
||||||
|
sort: { by: "value", direction: "desc" },
|
||||||
|
series: [{ name: "name", color: "teal.subtle" }],
|
||||||
|
})
|
||||||
|
|
||||||
|
return (
|
||||||
|
<BarList.Root chart={chart}>
|
||||||
|
<BarList.Content>
|
||||||
|
<BarList.Label title="Source" flex="1">
|
||||||
|
<BarList.Bar tooltip />
|
||||||
|
</BarList.Label>
|
||||||
|
<BarList.Label title="Visits" titleAlignment="end">
|
||||||
|
<BarList.Value />
|
||||||
|
</BarList.Label>
|
||||||
|
</BarList.Content>
|
||||||
|
</BarList.Root>
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
**With a custom value formatter:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<BarList.Value valueFormatter={(v) => `${(v / 1000).toFixed(0)}K`} />
|
||||||
|
```
|
||||||
|
|
||||||
|
**With multiple value columns:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<BarList.Label title="Visits" minW="16" titleAlignment="end">
|
||||||
|
<BarList.Value />
|
||||||
|
</BarList.Label>
|
||||||
|
<BarList.Label title="%" minW="12" titleAlignment="end">
|
||||||
|
<BarList.Value
|
||||||
|
valueFormatter={(v) =>
|
||||||
|
`${chart.getValuePercent("value", v).toFixed(0)}%`
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</BarList.Label>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## BarSegment
|
||||||
|
|
||||||
|
Single horizontal bar broken into colored segments. Good for showing how a total
|
||||||
|
is split across categories (budget, traffic, inventory).
|
||||||
|
|
||||||
|
**Data shape:**
|
||||||
|
|
||||||
|
```ts
|
||||||
|
interface BarSegmentData {
|
||||||
|
name: string // segment label
|
||||||
|
value: number // determines segment width
|
||||||
|
color: string // Chakra color token for this segment
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Basic example:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { BarSegment, useChart } from "@chakra-ui/charts"
|
||||||
|
|
||||||
|
const chart = useChart({
|
||||||
|
data: [
|
||||||
|
{ name: "Google", value: 500_000, color: "teal.solid" },
|
||||||
|
{ name: "Direct", value: 300_000, color: "blue.solid" },
|
||||||
|
{ name: "Twitter", value: 150_000, color: "purple.solid" },
|
||||||
|
{ name: "LinkedIn", value: 50_000, color: "orange.solid" },
|
||||||
|
],
|
||||||
|
sort: { by: "value", direction: "desc" },
|
||||||
|
})
|
||||||
|
|
||||||
|
return (
|
||||||
|
<BarSegment.Root chart={chart}>
|
||||||
|
<BarSegment.Content>
|
||||||
|
<BarSegment.Value />
|
||||||
|
<BarSegment.Bar tooltip />
|
||||||
|
<BarSegment.Label />
|
||||||
|
</BarSegment.Content>
|
||||||
|
<BarSegment.Legend showPercent showValue />
|
||||||
|
</BarSegment.Root>
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
**With a reference line (e.g. target):**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<BarSegment.Bar tooltip>
|
||||||
|
<BarSegment.Reference label="Target" value={600_000} />
|
||||||
|
</BarSegment.Bar>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Chart.Root + Recharts
|
||||||
|
|
||||||
|
Wrapper for any Recharts chart. Handles sizing, token resolution, and styled
|
||||||
|
tooltips and legends. You still compose the chart using standard Recharts
|
||||||
|
components — `BarChart`, `AreaChart`, `LineChart`, `PieChart`, etc.
|
||||||
|
|
||||||
|
### Bar chart
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { Chart, useChart } from "@chakra-ui/charts"
|
||||||
|
import {
|
||||||
|
Bar,
|
||||||
|
BarChart,
|
||||||
|
CartesianGrid,
|
||||||
|
Legend,
|
||||||
|
Tooltip,
|
||||||
|
XAxis,
|
||||||
|
YAxis,
|
||||||
|
} from "recharts"
|
||||||
|
|
||||||
|
const chart = useChart({
|
||||||
|
data: [
|
||||||
|
{ month: "Jan", revenue: 186, expenses: 80 },
|
||||||
|
{ month: "Feb", revenue: 165, expenses: 95 },
|
||||||
|
{ month: "Mar", revenue: 210, expenses: 110 },
|
||||||
|
],
|
||||||
|
series: [
|
||||||
|
{ name: "revenue", color: "teal.solid" },
|
||||||
|
{ name: "expenses", color: "orange.solid" },
|
||||||
|
],
|
||||||
|
})
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Chart.Root maxH="sm" chart={chart}>
|
||||||
|
<BarChart data={chart.data}>
|
||||||
|
<CartesianGrid stroke={chart.color("border.muted")} vertical={false} />
|
||||||
|
<XAxis dataKey={chart.key("month")} />
|
||||||
|
<YAxis />
|
||||||
|
<Tooltip cursor={false} content={<Chart.Tooltip />} />
|
||||||
|
<Legend content={<Chart.Legend />} />
|
||||||
|
{chart.series.map((item) => (
|
||||||
|
<Bar
|
||||||
|
key={item.name}
|
||||||
|
dataKey={chart.key(item.name)}
|
||||||
|
fill={chart.color(item.color)}
|
||||||
|
radius={4}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</BarChart>
|
||||||
|
</Chart.Root>
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Area chart
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { Area, AreaChart, CartesianGrid, Tooltip, XAxis } from "recharts"
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Chart.Root maxH="sm" chart={chart}>
|
||||||
|
<AreaChart data={chart.data}>
|
||||||
|
<defs>
|
||||||
|
{chart.series.map((item) => (
|
||||||
|
<Chart.Gradient
|
||||||
|
key={item.name}
|
||||||
|
id={item.name}
|
||||||
|
stops={[
|
||||||
|
{ offset: "0%", color: item.color, opacity: 0.2 },
|
||||||
|
{ offset: "100%", color: item.color, opacity: 0 },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</defs>
|
||||||
|
<CartesianGrid stroke={chart.color("border.muted")} vertical={false} />
|
||||||
|
<XAxis dataKey={chart.key("month")} />
|
||||||
|
<Tooltip cursor={false} content={<Chart.Tooltip />} />
|
||||||
|
{chart.series.map((item) => (
|
||||||
|
<Area
|
||||||
|
key={item.name}
|
||||||
|
dataKey={chart.key(item.name)}
|
||||||
|
stroke={chart.color(item.color)}
|
||||||
|
fill={`url(#${item.name})`}
|
||||||
|
stackId="a"
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</AreaChart>
|
||||||
|
</Chart.Root>
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Pie / donut chart
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { Pie, PieChart, Tooltip } from "recharts"
|
||||||
|
|
||||||
|
const chart = useChart({
|
||||||
|
data: [
|
||||||
|
{ browser: "Chrome", visitors: 275, color: "teal.solid" },
|
||||||
|
{ browser: "Safari", visitors: 200, color: "blue.solid" },
|
||||||
|
{ browser: "Firefox", visitors: 120, color: "orange.solid" },
|
||||||
|
{ browser: "Edge", visitors: 80, color: "purple.solid" },
|
||||||
|
],
|
||||||
|
series: [{ name: "visitors" }],
|
||||||
|
})
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Chart.Root maxH="sm" chart={chart}>
|
||||||
|
<PieChart>
|
||||||
|
<Tooltip content={<Chart.Tooltip hideLabel />} />
|
||||||
|
<Pie
|
||||||
|
data={chart.data}
|
||||||
|
dataKey={chart.key("visitors")}
|
||||||
|
nameKey={chart.key("browser")}
|
||||||
|
innerRadius="60%" // remove for a filled pie
|
||||||
|
paddingAngle={2}
|
||||||
|
>
|
||||||
|
{chart.data.map((item, index) => (
|
||||||
|
<Cell key={index} fill={chart.color(item.color)} />
|
||||||
|
))}
|
||||||
|
{/* Center text for donut */}
|
||||||
|
<Label
|
||||||
|
content={
|
||||||
|
<Chart.RadialText
|
||||||
|
viewBox={undefined}
|
||||||
|
title={chart.getTotal("visitors").toLocaleString()}
|
||||||
|
description="Total visitors"
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
position="center"
|
||||||
|
/>
|
||||||
|
</Pie>
|
||||||
|
</PieChart>
|
||||||
|
</Chart.Root>
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Chart sub-components
|
||||||
|
|
||||||
|
### `Chart.Tooltip`
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Tooltip
|
||||||
|
cursor={false}
|
||||||
|
content={
|
||||||
|
<Chart.Tooltip
|
||||||
|
showTotal // show sum of all series at bottom
|
||||||
|
hideLabel // hide the x-axis label row
|
||||||
|
hideSeriesLabel // hide series names
|
||||||
|
indicator="line" // "dot" | "line" | "dashed"
|
||||||
|
formatter={(value, name) => [`$${value}`, name]}
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
```
|
||||||
|
|
||||||
|
### `Chart.Legend`
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Legend
|
||||||
|
content={
|
||||||
|
<Chart.Legend
|
||||||
|
title="Channels"
|
||||||
|
interaction="click" // "hover" (default) | "click"
|
||||||
|
verticalAlign="top" // "top" | "bottom" (default)
|
||||||
|
align="right" // "left" | "center" (default) | "right"
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
```
|
||||||
|
|
||||||
|
Legend interaction highlights/dims series on hover or click.
|
||||||
|
|
||||||
|
### `Chart.Gradient`
|
||||||
|
|
||||||
|
Defines an SVG gradient for area fills. Must be inside a `<defs>` block:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<defs>
|
||||||
|
<Chart.Gradient
|
||||||
|
id="revenue-gradient"
|
||||||
|
stops={[
|
||||||
|
{ offset: "0%", color: "teal.solid", opacity: 0.3 },
|
||||||
|
{ offset: "100%", color: "teal.solid", opacity: 0 },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</defs>
|
||||||
|
|
||||||
|
<Area fill="url(#revenue-gradient)" ... />
|
||||||
|
```
|
||||||
|
|
||||||
|
### `Chart.RadialText`
|
||||||
|
|
||||||
|
Centers a title + description inside a pie or donut chart:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Label
|
||||||
|
content={
|
||||||
|
<Chart.RadialText
|
||||||
|
viewBox={undefined}
|
||||||
|
title="$1.2M"
|
||||||
|
description="Total revenue"
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
position="center"
|
||||||
|
/>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Colors and theming
|
||||||
|
|
||||||
|
All chart colors accept Chakra token strings or plain CSS colors:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// Chakra semantic tokens — respond to light/dark mode
|
||||||
|
color: "teal.solid"
|
||||||
|
color: "blue.subtle"
|
||||||
|
color: "border.muted" // useful for grid lines
|
||||||
|
|
||||||
|
// Palette steps
|
||||||
|
color: "blue.500"
|
||||||
|
|
||||||
|
// Raw CSS
|
||||||
|
color: "#3b82f6"
|
||||||
|
color: "hsl(210, 100%, 56%)"
|
||||||
|
```
|
||||||
|
|
||||||
|
Use `chart.color(token)` to resolve a token to a CSS value wherever Recharts
|
||||||
|
needs a string (e.g. `fill`, `stroke`, `CartesianGrid stroke`).
|
||||||
|
|
||||||
|
Recommended color tokens for multi-series charts:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
series: [
|
||||||
|
{ name: "a", color: "teal.solid" },
|
||||||
|
{ name: "b", color: "blue.solid" },
|
||||||
|
{ name: "c", color: "purple.solid" },
|
||||||
|
{ name: "d", color: "orange.solid" },
|
||||||
|
{ name: "e", color: "red.solid" },
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Output format
|
||||||
|
|
||||||
|
When building chart components:
|
||||||
|
|
||||||
|
1. Show the `useChart` setup and data shape first
|
||||||
|
2. Produce complete, runnable JSX with correct imports from both
|
||||||
|
`@chakra-ui/charts` and `recharts`
|
||||||
|
3. Use `chart.color("border.muted")` for grid lines so they respect dark mode
|
||||||
|
4. Default `Chart.Root` to `maxH="sm"` unless the user specifies a size
|
||||||
|
5. Include a `Tooltip` with `<Chart.Tooltip />` on every chart — it's almost
|
||||||
|
always wanted
|
||||||
|
6. Note the install command if the project doesn't already have
|
||||||
|
`@chakra-ui/charts`
|
||||||
@@ -0,0 +1,287 @@
|
|||||||
|
# Chakra UI Component Decision Tree
|
||||||
|
|
||||||
|
When the user hasn't specified a component, choose the most appropriate one
|
||||||
|
based on the guidelines below. Prefer an existing Chakra component over a custom
|
||||||
|
implementation. Match the interaction model first, then the visual treatment.
|
||||||
|
Prefer the narrowest component that fits — don't reach for `Box` when a more
|
||||||
|
specific primitive exists.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Layout and structure
|
||||||
|
|
||||||
|
- Use `Stack` (or `VStack`) for a vertical sequence of elements with consistent
|
||||||
|
spacing.
|
||||||
|
- Use `HStack` for a horizontal sequence of elements with consistent spacing.
|
||||||
|
- Use `Flex` when you need explicit control over flexbox properties (direction,
|
||||||
|
wrap, alignment).
|
||||||
|
- Use `Grid` + `GridItem` for two-dimensional layouts (rows and columns).
|
||||||
|
- Use `SimpleGrid` for equal-width columns that wrap automatically — good for
|
||||||
|
card grids and dashboards.
|
||||||
|
- Use `Container` to constrain page content to a max-width with horizontal
|
||||||
|
centering.
|
||||||
|
- Use `Center` to center content both horizontally and vertically without manual
|
||||||
|
flex setup.
|
||||||
|
- Use `AbsoluteCenter` when centering with `position: absolute` — useful for
|
||||||
|
overlays and loaders.
|
||||||
|
- Use `Card` when content is a self-contained unit that needs visual separation
|
||||||
|
(border, shadow, padding). Use `Box` only when no built-in container semantics
|
||||||
|
apply.
|
||||||
|
- Use `Wrap` for tag clouds, badge sets, or button groups that should flow and
|
||||||
|
wrap automatically.
|
||||||
|
- Use `Spacer` inside `Flex` to push elements to opposite ends.
|
||||||
|
- Use `Group` to visually merge related elements (buttons, inputs) into a single
|
||||||
|
bordered unit.
|
||||||
|
- Use `Bleed` to extend a background or image beyond the padding of its parent
|
||||||
|
container.
|
||||||
|
- Use `Splitter` when the user should be able to resize two adjacent panels.
|
||||||
|
- Use `ScrollArea` for a container that needs custom cross-browser styled
|
||||||
|
scrollbars.
|
||||||
|
- Use `AspectRatio` to lock a child element (video, image, map) to a fixed
|
||||||
|
aspect ratio.
|
||||||
|
|
||||||
|
### Stack vs Flex vs Grid
|
||||||
|
|
||||||
|
- Choose `Stack` or `HStack`/`VStack` for uniform spacing along one axis — it's
|
||||||
|
the most common case.
|
||||||
|
- Choose `Flex` when you need `flexWrap`, `justifyContent`, `alignItems`, or
|
||||||
|
other flex properties beyond spacing.
|
||||||
|
- Choose `Grid` when you need to position elements across both rows and columns
|
||||||
|
at the same time.
|
||||||
|
- Choose `SimpleGrid` when you only need responsive equal-width columns and
|
||||||
|
nothing more.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Typography
|
||||||
|
|
||||||
|
- Use `Heading` for page and section titles (`h1`–`h6`). Don't use `Text` as a
|
||||||
|
heading shortcut.
|
||||||
|
- Use `Text` for body copy, labels, and descriptive text.
|
||||||
|
- Use `Span` for inline styled text inside a paragraph.
|
||||||
|
- Use `Em` and `Strong` for semantically emphasized or important text.
|
||||||
|
- Use `Mark` for highlighted text (e.g. search result matches).
|
||||||
|
- Use `Code` for short inline code snippets.
|
||||||
|
- Use `CodeBlock` for multi-line code with copy button and optional collapse —
|
||||||
|
not for single-line snippets.
|
||||||
|
- Use `Kbd` to display keyboard shortcuts.
|
||||||
|
- Use `Blockquote` for pull quotes with attribution.
|
||||||
|
- Use `Highlight` to highlight matching substrings dynamically in text.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Actions and links
|
||||||
|
|
||||||
|
- Use `Button` for primary and secondary actions (form submissions,
|
||||||
|
confirmations, key page actions).
|
||||||
|
- Use `IconButton` for icon-only actions — always provide `aria-label`.
|
||||||
|
- Use `CloseButton` for dismiss/close actions in dialogs, drawers, and toasts.
|
||||||
|
- Use `ButtonGroup` to group related actions (e.g. Save / Cancel) with
|
||||||
|
consistent sizing and variant.
|
||||||
|
- Use `Link` for text navigation — inline within a sentence or standalone. Use
|
||||||
|
`asChild` with Next.js `<Link>` in App Router projects.
|
||||||
|
- Use `LinkBox` + `LinkOverlay` to make an entire card or row clickable while
|
||||||
|
preserving accessible markup.
|
||||||
|
- Use `Toggle` when a button should visually represent an on/off pressed state.
|
||||||
|
- Use `Switch` (not `Toggle`) when the interaction is a persistent on/off
|
||||||
|
setting (e.g. enable notifications).
|
||||||
|
- Use `DownloadTrigger` for file download buttons.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Choosing from options
|
||||||
|
|
||||||
|
- Use `Switch` for turning a single setting on or off.
|
||||||
|
- Use `Checkbox` for a single independent yes/no option. Use `CheckboxGroup` for
|
||||||
|
a set of independent options where many can be selected.
|
||||||
|
- Use `CheckboxCard` over `Checkbox` when the option needs a title, description,
|
||||||
|
or more visual emphasis.
|
||||||
|
- Use `RadioGroup` for mutually exclusive options when 2–4 options should always
|
||||||
|
be visible.
|
||||||
|
- Use `RadioCard` over `RadioGroup` when each option benefits from a
|
||||||
|
description, icon, or richer presentation.
|
||||||
|
- Use `SegmentGroup` for a compact mutually exclusive mode/view switch
|
||||||
|
(iOS-style segmented control) — typically 2–4 options.
|
||||||
|
- Use `NativeSelect` for mobile-first dropdowns where the platform picker is
|
||||||
|
preferred.
|
||||||
|
- Use `Select` for styled dropdowns with full design control — prefer over
|
||||||
|
`NativeSelect` on desktop.
|
||||||
|
- Use `Combobox` when the user should type to filter a long list or search
|
||||||
|
options — prefer over `Select` for lists longer than ~15 items.
|
||||||
|
- Use `Listbox` when options must always be visible and scrollable without a
|
||||||
|
dropdown trigger.
|
||||||
|
- Use `TagsInput` for entering multiple free-form or autocompleted values
|
||||||
|
(skills, labels, emails).
|
||||||
|
- Use `RatingGroup` for star or point ratings.
|
||||||
|
|
||||||
|
### Select vs Combobox vs NativeSelect
|
||||||
|
|
||||||
|
- Choose `NativeSelect` for mobile-first or form-heavy interfaces where native
|
||||||
|
picker behavior is expected.
|
||||||
|
- Choose `Select` for styled dropdowns on desktop with a known, bounded list.
|
||||||
|
- Choose `Combobox` when filtering/searching is important or the list is long.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Text and value input
|
||||||
|
|
||||||
|
- Use `Input` for single-line plain text.
|
||||||
|
- Use `Textarea` for multi-line text.
|
||||||
|
- Use `NumberInput` for numeric entry with increment/decrement controls.
|
||||||
|
- Use `Slider` for adjusting a value when direct manipulation is preferred over
|
||||||
|
exact entry. Use a range slider (dual thumbs) for min/max ranges.
|
||||||
|
- Use `PinInput` for fixed-length codes — OTP verification, PIN entry. It
|
||||||
|
auto-advances focus between fields.
|
||||||
|
- Use `Editable` for click-to-edit inline text — useful for titles,
|
||||||
|
descriptions, and table cells.
|
||||||
|
- Use `DatePicker` when a calendar popover should assist with date selection.
|
||||||
|
- Use `ColorPicker` for full color selection with RGB/HSL/hex modes and
|
||||||
|
eyedropper.
|
||||||
|
- Use `FileUpload` for file selection with drag-and-drop and preview.
|
||||||
|
- Use `Clipboard` for copy-to-clipboard functionality with visual feedback.
|
||||||
|
- Use `Field.Root` to wrap every form input — it wires up the label, helper
|
||||||
|
text, error text, and required indicator correctly.
|
||||||
|
- Use `InputGroup` to attach prefix/suffix addons (icons, currency symbols,
|
||||||
|
units) to an `Input`.
|
||||||
|
- Use `Fieldset` to group semantically related form fields under a shared
|
||||||
|
legend.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Overlays and pop-ups
|
||||||
|
|
||||||
|
- Use `Tooltip` for a short text description of a focusable element. Don't put
|
||||||
|
interactive content in a tooltip.
|
||||||
|
- Use `HoverCard` for richer preview content on hover (user profiles, link
|
||||||
|
previews) — more than a tooltip, less than a popover.
|
||||||
|
- Use `Popover` for interactive contextual content anchored to a trigger —
|
||||||
|
forms, filters, settings panels.
|
||||||
|
- Use `Dialog` for modal tasks that require user attention before continuing.
|
||||||
|
- Use `Drawer` for off-canvas panels — navigation, detail views, settings — when
|
||||||
|
modal behavior is needed but the content is beside rather than over the page.
|
||||||
|
- Use `Toast` for brief transient feedback after an action (saved, error,
|
||||||
|
copied). Use the `Toaster` component to render stacked toasts.
|
||||||
|
- Use `ActionBar` for mobile-style bulk action bars that appear after selection.
|
||||||
|
- Use `Menu` for action menus triggered by a button — "more options",
|
||||||
|
right-click menus. Use `Menu.CheckboxItem` and `Menu.RadioItem` for
|
||||||
|
toggle/selection actions within a menu.
|
||||||
|
|
||||||
|
### Tooltip vs HoverCard vs Popover
|
||||||
|
|
||||||
|
- Choose `Tooltip` for a single line of non-interactive help text.
|
||||||
|
- Choose `HoverCard` for hover-triggered preview cards with structured content.
|
||||||
|
- Choose `Popover` when the floating content needs to be interactive (has
|
||||||
|
buttons, inputs, or links).
|
||||||
|
|
||||||
|
### Dialog vs Drawer
|
||||||
|
|
||||||
|
- Choose `Dialog` when the overlay should be centered, blocking, and focus
|
||||||
|
attention on a specific task or confirmation.
|
||||||
|
- Choose `Drawer` when the content slides in from an edge and relates to what's
|
||||||
|
already on screen (details, navigation, filters).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Disclosure and navigation
|
||||||
|
|
||||||
|
- Use `Accordion` for a set of related collapsible sections where only one (or a
|
||||||
|
few) should be open at a time — FAQs, grouped settings.
|
||||||
|
- Use `Collapsible` for a single expandable section — don't use `Accordion` with
|
||||||
|
one item.
|
||||||
|
- Use `Tabs` for peer content panels where switching shows one panel at a time —
|
||||||
|
prefer for horizontal layouts.
|
||||||
|
- Use `SegmentGroup` instead of `Tabs` when switching modes or views rather than
|
||||||
|
showing different full content panels.
|
||||||
|
- Use `Steps` for multi-step wizards and onboarding flows — shows progress and
|
||||||
|
allows back/next navigation.
|
||||||
|
- Use `Breadcrumb` to show the user's location in a hierarchy.
|
||||||
|
- Use `Pagination` for navigating paged datasets.
|
||||||
|
- Use `Menu` for dropdown navigation menus.
|
||||||
|
- Use `TreeView` when a file-system-style hierarchy must stay visible and
|
||||||
|
expandable in place.
|
||||||
|
|
||||||
|
### Accordion vs Tabs vs Collapsible
|
||||||
|
|
||||||
|
- Choose `Accordion` for vertically stacked collapsible sections (FAQs, settings
|
||||||
|
groups).
|
||||||
|
- Choose `Tabs` for horizontal peer sections where all tabs are always visible.
|
||||||
|
- Choose `Collapsible` for a single show/hide section — not a group.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Data display
|
||||||
|
|
||||||
|
- Use `Table` for structured tabular data with rows and columns — sortable
|
||||||
|
headers, dense comparison.
|
||||||
|
- Use `DataList` for key-value pairs (user profile details, metadata) — not true
|
||||||
|
tabular data.
|
||||||
|
- Use `Stat` + `StatGroup` for KPI metrics and dashboard numbers with up/down
|
||||||
|
indicators.
|
||||||
|
- Use `Timeline` for chronological events, changelogs, or process steps.
|
||||||
|
- Use `Badge` for compact non-removable status labels (Active, Beta, New).
|
||||||
|
- Use `Tag` over `Badge` when the label should be removable or interactive.
|
||||||
|
- Use `Avatar` + `AvatarGroup` for user profile pictures with fallback initials
|
||||||
|
or icon.
|
||||||
|
- Use `Carousel` for image galleries, feature showcases, or content sliders.
|
||||||
|
- Use `QrCode` to render a QR code from a string value.
|
||||||
|
- Use `ColorSwatch` to display a color value visually.
|
||||||
|
|
||||||
|
### Table vs DataList
|
||||||
|
|
||||||
|
- Choose `Table` when data has multiple comparable columns and rows.
|
||||||
|
- Choose `DataList` for a single record's attributes displayed as label/value
|
||||||
|
pairs.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Feedback and status
|
||||||
|
|
||||||
|
- Use `Alert` for persistent in-page messages (warnings, info, errors) that are
|
||||||
|
part of the page layout.
|
||||||
|
- Use `Toast` for transient post-action feedback — it disappears automatically.
|
||||||
|
- Use `EmptyState` for no-data and no-results states — provides structured
|
||||||
|
layout for illustration, title, description, and actions.
|
||||||
|
- Use `Spinner` for indeterminate loading — content is fetching, duration
|
||||||
|
unknown.
|
||||||
|
- Use `Skeleton` for loading placeholders that approximate the shape of incoming
|
||||||
|
content.
|
||||||
|
- Use `Progress` for a linear progress bar on an operation with a known
|
||||||
|
completion percentage.
|
||||||
|
- Use `ProgressCircle` for the same use case when a circular indicator fits the
|
||||||
|
layout better.
|
||||||
|
- Use `Loader` as an alternative to `Spinner` for a different visual style of
|
||||||
|
indeterminate loading.
|
||||||
|
|
||||||
|
### Alert vs Toast vs EmptyState
|
||||||
|
|
||||||
|
- Choose `Alert` when the message is persistent and tied to content on the
|
||||||
|
current view.
|
||||||
|
- Choose `Toast` when the message is temporary and triggered by a user action.
|
||||||
|
- Choose `EmptyState` when there is no content to display and you want to
|
||||||
|
explain why and offer a next action.
|
||||||
|
|
||||||
|
### Spinner vs Skeleton vs Progress
|
||||||
|
|
||||||
|
- Choose `Spinner` when loading is happening and the layout isn't known yet.
|
||||||
|
- Choose `Skeleton` when the layout is known — show placeholder shapes that
|
||||||
|
match the expected content.
|
||||||
|
- Choose `Progress` when the operation has a measurable percentage.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Utilities
|
||||||
|
|
||||||
|
- Use `VisuallyHidden` for screen-reader-only text — skip links, icon button
|
||||||
|
labels added outside the button.
|
||||||
|
- Use `SkipNav` to add a skip-to-main-content accessibility link.
|
||||||
|
- Use `Portal` when a component must render outside its DOM parent to avoid
|
||||||
|
z-index or overflow clipping issues.
|
||||||
|
- Use `FocusTrap` to constrain keyboard focus within a region (custom modals,
|
||||||
|
custom drawers).
|
||||||
|
- Use `Presence` to animate components on mount and unmount.
|
||||||
|
- Use `Show` / `Hide` for responsive conditional rendering based on breakpoints.
|
||||||
|
- Use `For` as a typed loop utility when rendering lists of components.
|
||||||
|
- Use `ClientOnly` to prevent SSR hydration mismatches for browser-only content.
|
||||||
|
- Use `FormatNumber` / `FormatByte` for locale-aware number and file-size
|
||||||
|
formatting.
|
||||||
|
- Use `Marquee` for scrolling announcement banners or news tickers.
|
||||||
@@ -0,0 +1,331 @@
|
|||||||
|
# Chakra UI Theming Reference
|
||||||
|
|
||||||
|
Use v3 patterns (`defineConfig`, `createSystem`, `defineRecipe`,
|
||||||
|
`defineSlotRecipe`) by default. Only use v2 patterns (`extendTheme`,
|
||||||
|
`styleConfig`) if the project is explicitly on v2.
|
||||||
|
|
||||||
|
Before starting, check `package.json` for the Chakra UI version and look for an
|
||||||
|
existing theme file (`theme.ts`, `system.ts`) to understand what's already
|
||||||
|
defined.
|
||||||
|
|
||||||
|
Clarify scope when needed:
|
||||||
|
|
||||||
|
- **Full design system** — tokens, semantic tokens, and component recipes from
|
||||||
|
scratch
|
||||||
|
- **Partial update** — adding or changing specific tokens or recipes
|
||||||
|
- **Single recipe** — one component's styles with variants
|
||||||
|
- **Typegen only** — running `@chakra-ui/cli typegen` after custom additions
|
||||||
|
|
||||||
|
If the user says "add my brand colors" without specifying the colors, ask first.
|
||||||
|
A partial answer is worse than pausing to clarify.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## System setup: `defineConfig` and `createSystem`
|
||||||
|
|
||||||
|
All theming in v3 starts with `createSystem`. Use `defineConfig` to author
|
||||||
|
customizations, then merge with `defaultConfig`:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// theme.ts
|
||||||
|
import { createSystem, defaultConfig, defineConfig } from "@chakra-ui/react"
|
||||||
|
|
||||||
|
const config = defineConfig({
|
||||||
|
theme: {
|
||||||
|
tokens: {
|
||||||
|
/* ... */
|
||||||
|
},
|
||||||
|
semanticTokens: {
|
||||||
|
/* ... */
|
||||||
|
},
|
||||||
|
recipes: {
|
||||||
|
/* ... */
|
||||||
|
},
|
||||||
|
slotRecipes: {
|
||||||
|
/* ... */
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
export const system = createSystem(defaultConfig, config)
|
||||||
|
```
|
||||||
|
|
||||||
|
Pass `system` to `ChakraProvider`:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// components/ui/provider.tsx
|
||||||
|
"use client"
|
||||||
|
import { system } from "@/theme"
|
||||||
|
import { ChakraProvider } from "@chakra-ui/react"
|
||||||
|
|
||||||
|
export function Provider({ children }) {
|
||||||
|
return <ChakraProvider value={system}>{children}</ChakraProvider>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Tokens
|
||||||
|
|
||||||
|
Tokens are the raw, concrete values in your design system — the foundation
|
||||||
|
everything else references.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
const config = defineConfig({
|
||||||
|
theme: {
|
||||||
|
tokens: {
|
||||||
|
colors: {
|
||||||
|
brand: {
|
||||||
|
50: { value: "#eff6ff" },
|
||||||
|
100: { value: "#dbeafe" },
|
||||||
|
200: { value: "#bfdbfe" },
|
||||||
|
500: { value: "#3b82f6" },
|
||||||
|
600: { value: "#2563eb" },
|
||||||
|
700: { value: "#1d4ed8" },
|
||||||
|
900: { value: "#1e3a8a" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
fonts: {
|
||||||
|
heading: { value: "var(--font-geist-sans), sans-serif" },
|
||||||
|
body: { value: "var(--font-geist-sans), sans-serif" },
|
||||||
|
mono: { value: "var(--font-geist-mono), monospace" },
|
||||||
|
},
|
||||||
|
fontSizes: {
|
||||||
|
xs: { value: "0.75rem" },
|
||||||
|
sm: { value: "0.875rem" },
|
||||||
|
md: { value: "1rem" },
|
||||||
|
lg: { value: "1.125rem" },
|
||||||
|
xl: { value: "1.25rem" },
|
||||||
|
"2xl": { value: "1.5rem" },
|
||||||
|
},
|
||||||
|
radii: {
|
||||||
|
sm: { value: "0.25rem" },
|
||||||
|
md: { value: "0.375rem" },
|
||||||
|
lg: { value: "0.5rem" },
|
||||||
|
xl: { value: "0.75rem" },
|
||||||
|
full: { value: "9999px" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Use scale-based keys for palettes (`50`, `100`, …, `900`) and semantic keys for
|
||||||
|
single values (`sm`, `md`, `lg`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Semantic tokens
|
||||||
|
|
||||||
|
Semantic tokens reference base tokens and assign _meaning_ to them. Their key
|
||||||
|
feature: different values per color mode, making dark mode automatic.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
const config = defineConfig({
|
||||||
|
theme: {
|
||||||
|
semanticTokens: {
|
||||||
|
colors: {
|
||||||
|
"brand.solid": {
|
||||||
|
value: { base: "{colors.brand.600}", _dark: "{colors.brand.400}" },
|
||||||
|
},
|
||||||
|
"brand.muted": {
|
||||||
|
value: { base: "{colors.brand.100}", _dark: "{colors.brand.900}" },
|
||||||
|
},
|
||||||
|
"brand.subtle": {
|
||||||
|
value: { base: "{colors.brand.50}", _dark: "{colors.brand.950}" },
|
||||||
|
},
|
||||||
|
|
||||||
|
"bg.default": { value: { base: "white", _dark: "{colors.gray.900}" } },
|
||||||
|
"bg.subtle": {
|
||||||
|
value: { base: "{colors.gray.50}", _dark: "{colors.gray.800}" },
|
||||||
|
},
|
||||||
|
"bg.muted": {
|
||||||
|
value: { base: "{colors.gray.100}", _dark: "{colors.gray.700}" },
|
||||||
|
},
|
||||||
|
|
||||||
|
"fg.default": { value: { base: "{colors.gray.900}", _dark: "white" } },
|
||||||
|
"fg.muted": {
|
||||||
|
value: { base: "{colors.gray.600}", _dark: "{colors.gray.400}" },
|
||||||
|
},
|
||||||
|
"fg.subtle": {
|
||||||
|
value: { base: "{colors.gray.400}", _dark: "{colors.gray.600}" },
|
||||||
|
},
|
||||||
|
|
||||||
|
"border.default": {
|
||||||
|
value: { base: "{colors.gray.200}", _dark: "{colors.gray.700}" },
|
||||||
|
},
|
||||||
|
"border.muted": {
|
||||||
|
value: { base: "{colors.gray.100}", _dark: "{colors.gray.800}" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Components that use `bg="bg.subtle"` instead of `bg="gray.50"` automatically get
|
||||||
|
the correct dark mode value — no conditional logic needed. Build on semantic
|
||||||
|
tokens wherever possible.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Recipes (single-component styles)
|
||||||
|
|
||||||
|
Recipes replace `styleConfig` from v2. Use them when a single component has
|
||||||
|
meaningful style variants that developers will reuse across the project.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { defineRecipe } from "@chakra-ui/react"
|
||||||
|
|
||||||
|
export const badgeRecipe = defineRecipe({
|
||||||
|
base: {
|
||||||
|
display: "inline-flex",
|
||||||
|
alignItems: "center",
|
||||||
|
px: 2,
|
||||||
|
py: 0.5,
|
||||||
|
borderRadius: "full",
|
||||||
|
fontSize: "xs",
|
||||||
|
fontWeight: "medium",
|
||||||
|
},
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
solid: { bg: "colorPalette.500", color: "white" },
|
||||||
|
subtle: { bg: "colorPalette.100", color: "colorPalette.800" },
|
||||||
|
outline: {
|
||||||
|
borderWidth: 1,
|
||||||
|
borderColor: "colorPalette.500",
|
||||||
|
color: "colorPalette.600",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
size: {
|
||||||
|
sm: { px: 1.5, py: 0.5, fontSize: "2xs" },
|
||||||
|
md: { px: 2, py: 0.5, fontSize: "xs" },
|
||||||
|
lg: { px: 3, py: 1, fontSize: "sm" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: { variant: "subtle", size: "md" },
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Register in the theme config:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
const config = defineConfig({ theme: { recipes: { badge: badgeRecipe } } })
|
||||||
|
```
|
||||||
|
|
||||||
|
`colorPalette` inside a recipe is a placeholder — it resolves to whatever
|
||||||
|
`colorPalette` prop the consumer passes (`colorPalette="blue"` → `blue.500`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Slot recipes (multi-part components)
|
||||||
|
|
||||||
|
Slot recipes replace `multiStyleConfig` from v2. Use them when a component has
|
||||||
|
multiple coordinated parts that all respond to the same variants.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { defineSlotRecipe } from "@chakra-ui/react"
|
||||||
|
|
||||||
|
export const cardSlotRecipe = defineSlotRecipe({
|
||||||
|
slots: ["root", "header", "body", "footer", "title"],
|
||||||
|
base: {
|
||||||
|
root: { bg: "bg.surface", rounded: "xl", overflow: "hidden", shadow: "sm" },
|
||||||
|
header: { px: 6, py: 4, borderBottomWidth: 1, borderColor: "border.muted" },
|
||||||
|
body: { px: 6, py: 4 },
|
||||||
|
footer: { px: 6, py: 4, borderTopWidth: 1, borderColor: "border.muted" },
|
||||||
|
title: { fontSize: "lg", fontWeight: "semibold", color: "fg.default" },
|
||||||
|
},
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
elevated: { root: { shadow: "md" } },
|
||||||
|
outline: {
|
||||||
|
root: { shadow: "none", borderWidth: 1, borderColor: "border.default" },
|
||||||
|
},
|
||||||
|
filled: { root: { bg: "bg.subtle", shadow: "none" } },
|
||||||
|
},
|
||||||
|
size: {
|
||||||
|
sm: {
|
||||||
|
root: { rounded: "lg" },
|
||||||
|
body: { px: 4, py: 3 },
|
||||||
|
header: { px: 4, py: 3 },
|
||||||
|
},
|
||||||
|
md: {},
|
||||||
|
lg: { body: { px: 8, py: 6 }, header: { px: 8, py: 6 } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: { variant: "elevated", size: "md" },
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Register:
|
||||||
|
`const config = defineConfig({ theme: { slotRecipes: { card: cardSlotRecipe } } })`
|
||||||
|
|
||||||
|
Consume with `useSlotRecipe`:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { useSlotRecipe } from "@chakra-ui/react"
|
||||||
|
|
||||||
|
function Card({ variant = "elevated", size = "md", children }) {
|
||||||
|
const recipe = useSlotRecipe({ key: "card" })
|
||||||
|
const styles = recipe({ variant, size })
|
||||||
|
return <Box css={styles.root}>{children}</Box>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Typegen
|
||||||
|
|
||||||
|
Run typegen after adding custom tokens, semantic tokens, recipes, or slot
|
||||||
|
recipes. Without it, TypeScript won't know your custom values exist.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx @chakra-ui/cli typegen ./theme.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
| Flag | Effect |
|
||||||
|
| ------------------- | ------------------------------------------------------------- |
|
||||||
|
| `--strict` | Strict literal types for variant and size props (recommended) |
|
||||||
|
| `--watch` | Re-runs automatically whenever the theme file changes |
|
||||||
|
| `--outdir <dir>` | Custom output directory for generated types |
|
||||||
|
| `--tsconfig <path>` | Path to tsconfig when using path aliases |
|
||||||
|
|
||||||
|
For active development: `npx @chakra-ui/cli typegen ./theme.ts --watch`
|
||||||
|
|
||||||
|
Typegen is required when you've added custom color tokens, semantic tokens,
|
||||||
|
spacing/font/radius tokens, or new recipes or slot recipes.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Ejecting the default theme
|
||||||
|
|
||||||
|
For full control over Chakra's built-in tokens, recipes, and styles:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx @chakra-ui/cli eject
|
||||||
|
```
|
||||||
|
|
||||||
|
Writes the complete default theme into a `theme/` directory (`--outdir <dir>` to
|
||||||
|
override), including separate files for tokens, semantic tokens, recipes, slot
|
||||||
|
recipes, text styles, layer styles, and animation styles — all as editable
|
||||||
|
`defineConfig` exports.
|
||||||
|
|
||||||
|
Use `eject` when modifying built-in component recipes or replacing large parts
|
||||||
|
of the default token scale. For smaller customizations (adding brand colors,
|
||||||
|
overriding a few tokens), extending with `defineConfig` is simpler.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Output format
|
||||||
|
|
||||||
|
Produce:
|
||||||
|
|
||||||
|
1. **Complete theme config** — `defineConfig` with all relevant sections
|
||||||
|
2. **Proper imports** — `defineConfig`, `createSystem`, `defineRecipe`, etc.
|
||||||
|
from `@chakra-ui/react`
|
||||||
|
3. **Provider wiring** — how to pass `system` to `ChakraProvider` if needed
|
||||||
|
4. **Usage examples** — show tokens/recipes consumed in a component
|
||||||
|
5. **Typegen reminder** — note when to run typegen
|
||||||
|
|
||||||
|
Brief explanation after the code (2–4 sentences) on key decisions. Skip for
|
||||||
|
trivial requests.
|
||||||
@@ -0,0 +1,494 @@
|
|||||||
|
---
|
||||||
|
name: chakra-ui-migrate
|
||||||
|
description: >
|
||||||
|
Migrate Chakra UI projects from v2 to v3, covering package changes, codemods,
|
||||||
|
provider setup, color mode, prop renaming, compound components, theming,
|
||||||
|
recipes, and Next.js updates. Use this skill whenever a user is upgrading
|
||||||
|
Chakra UI versions, encountering breaking changes after an upgrade, converting
|
||||||
|
old v2 patterns (ColorModeScript, useColorModeValue, styleConfig, extendTheme,
|
||||||
|
isDisabled, colorScheme, @chakra-ui/icons, framer-motion dependency), fixing
|
||||||
|
compound component patterns, or asking about differences between Chakra UI v2
|
||||||
|
and v3 — even if they don't say "migrate" or "upgrade" explicitly.
|
||||||
|
---
|
||||||
|
|
||||||
|
# Chakra UI Migration: v2 → v3
|
||||||
|
|
||||||
|
You are guiding a developer through migrating their project from Chakra UI v2 to
|
||||||
|
v3. Work through the steps below in order. Inspect the project first — never
|
||||||
|
guess the package versions or framework.
|
||||||
|
|
||||||
|
> **Node requirement:** Chakra UI v3 requires Node >= 20.x. Confirm before
|
||||||
|
> proceeding if the environment is uncertain.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 1 — Inspect the project
|
||||||
|
|
||||||
|
Read these files to understand the current state:
|
||||||
|
|
||||||
|
```
|
||||||
|
package.json
|
||||||
|
```
|
||||||
|
|
||||||
|
Look for:
|
||||||
|
|
||||||
|
- Current `@chakra-ui/react` version (v2.x vs v3.x)
|
||||||
|
- Related packages: `@chakra-ui/icons`, `@chakra-ui/hooks`,
|
||||||
|
`@chakra-ui/next-js`, `@emotion/styled`, `framer-motion`
|
||||||
|
- Framework: Next.js (App Router or Pages Router), Vite, plain React
|
||||||
|
- Package manager (from lockfiles: `pnpm-lock.yaml`, `yarn.lock`, `bun.lock`,
|
||||||
|
`package-lock.json`)
|
||||||
|
|
||||||
|
Also spot-check key files when helpful:
|
||||||
|
|
||||||
|
- Provider / theme setup (`_app.tsx`, `layout.tsx`, `theme.ts`)
|
||||||
|
- Color mode usage (`ColorModeScript`, `useColorMode`, `useColorModeValue`)
|
||||||
|
- Any component files showing heavy v2 patterns
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 2 — Update packages
|
||||||
|
|
||||||
|
### Remove v2-only dependencies
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# npm
|
||||||
|
npm uninstall @chakra-ui/icons @chakra-ui/hooks @chakra-ui/next-js @emotion/styled framer-motion
|
||||||
|
|
||||||
|
# pnpm
|
||||||
|
pnpm remove @chakra-ui/icons @chakra-ui/hooks @chakra-ui/next-js @emotion/styled framer-motion
|
||||||
|
|
||||||
|
# yarn
|
||||||
|
yarn remove @chakra-ui/icons @chakra-ui/hooks @chakra-ui/next-js @emotion/styled framer-motion
|
||||||
|
```
|
||||||
|
|
||||||
|
`@emotion/styled` and `framer-motion` are no longer required in v3.
|
||||||
|
|
||||||
|
### Install v3 core packages
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# npm
|
||||||
|
npm install @chakra-ui/react @emotion/react
|
||||||
|
|
||||||
|
# pnpm
|
||||||
|
pnpm add @chakra-ui/react @emotion/react
|
||||||
|
|
||||||
|
# yarn
|
||||||
|
yarn add @chakra-ui/react @emotion/react
|
||||||
|
```
|
||||||
|
|
||||||
|
### Replacements for removed packages
|
||||||
|
|
||||||
|
| Removed | Replacement |
|
||||||
|
| -------------------- | -------------------------------------------- |
|
||||||
|
| `@chakra-ui/icons` | `lucide-react` or `react-icons` |
|
||||||
|
| `@chakra-ui/hooks` | `react-use` or `usehooks-ts` |
|
||||||
|
| `@chakra-ui/next-js` | `asChild` prop pattern (see Next.js section) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 3 — Run the codemod
|
||||||
|
|
||||||
|
The official codemod handles most mechanical changes: component renames, prop
|
||||||
|
updates, import rewrites, and compound component restructuring. It does not
|
||||||
|
replace manual review — plan to audit the output.
|
||||||
|
|
||||||
|
**Dry run first (no files changed):**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx @chakra-ui/codemod upgrade --dry
|
||||||
|
```
|
||||||
|
|
||||||
|
Review what it proposes. When satisfied:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx @chakra-ui/codemod upgrade
|
||||||
|
```
|
||||||
|
|
||||||
|
After the codemod, commit the changes before making manual edits so you have a
|
||||||
|
clean diff to work from.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 4 — Update the Provider
|
||||||
|
|
||||||
|
### Old v2 pattern
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// v2
|
||||||
|
import { ChakraProvider } from "@chakra-ui/react"
|
||||||
|
import theme from "./theme"
|
||||||
|
|
||||||
|
;<ChakraProvider theme={theme}>{children}</ChakraProvider>
|
||||||
|
```
|
||||||
|
|
||||||
|
### New v3 pattern (using Chakra CLI snippets)
|
||||||
|
|
||||||
|
Generate the provider and component snippets:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx @chakra-ui/cli snippet add
|
||||||
|
```
|
||||||
|
|
||||||
|
This creates `components/ui/provider.tsx` (plus `toaster` and `tooltip`
|
||||||
|
snippets) and automatically installs required npm dependencies — including
|
||||||
|
`next-themes`. Import and use it:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// v3 — app/layout.tsx (Next.js App Router)
|
||||||
|
import { Provider } from "@/components/ui/provider"
|
||||||
|
|
||||||
|
;<html lang="en" suppressHydrationWarning>
|
||||||
|
<body>
|
||||||
|
<Provider>{children}</Provider>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
```
|
||||||
|
|
||||||
|
The `Provider` file includes `"use client"` — do not add it to `layout.tsx`. See
|
||||||
|
the Next.js section for Pages Router placement.
|
||||||
|
|
||||||
|
### Custom theme in v3
|
||||||
|
|
||||||
|
Replace `extendTheme` with `createSystem`:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// v2
|
||||||
|
import { extendTheme } from "@chakra-ui/react"
|
||||||
|
// v3
|
||||||
|
import { createSystem, defaultConfig, defineConfig } from "@chakra-ui/react"
|
||||||
|
|
||||||
|
export const theme = extendTheme({ colors: { brand: { 500: "#2196f3" } } })
|
||||||
|
|
||||||
|
const config = defineConfig({
|
||||||
|
theme: { tokens: { colors: { brand: { 500: { value: "#2196f3" } } } } },
|
||||||
|
})
|
||||||
|
export const system = createSystem(defaultConfig, config)
|
||||||
|
```
|
||||||
|
|
||||||
|
Pass `system` to `ChakraProvider` via `value={system}`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 5 — Color mode migration
|
||||||
|
|
||||||
|
### Remove all v2 color mode patterns
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// REMOVE these v2 imports and usages:
|
||||||
|
import { ColorModeScript } from "@chakra-ui/react"
|
||||||
|
// ❌
|
||||||
|
import { useColorMode } from "@chakra-ui/react"
|
||||||
|
// ❌ (use next-themes)
|
||||||
|
import { useColorModeValue } from "@chakra-ui/react"
|
||||||
|
// ❌ (use CSS tokens)
|
||||||
|
import { DarkMode, LightMode } from "@chakra-ui/react"
|
||||||
|
|
||||||
|
// ❌
|
||||||
|
|
||||||
|
// Also remove from _document.tsx:
|
||||||
|
;<ColorModeScript initialColorMode={theme.config.initialColorMode} /> // ❌
|
||||||
|
```
|
||||||
|
|
||||||
|
### v3 color mode approach
|
||||||
|
|
||||||
|
Color mode is handled by `next-themes` via the generated `Provider`. Use
|
||||||
|
semantic tokens that automatically respond to the active color mode:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Use Chakra semantic tokens — they flip automatically in dark mode
|
||||||
|
<Box color="fg.default" bg="bg.subtle">
|
||||||
|
...
|
||||||
|
</Box>
|
||||||
|
```
|
||||||
|
|
||||||
|
For a color mode toggle, use the generated `components/ui/color-mode.tsx`
|
||||||
|
snippet or `useColorMode` from `next-themes` directly.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 6 — Prop renames
|
||||||
|
|
||||||
|
These boolean and style props were renamed in v3 for consistency with HTML and
|
||||||
|
modern React conventions. The codemod catches most of these, but verify manually
|
||||||
|
afterward.
|
||||||
|
|
||||||
|
### Boolean props
|
||||||
|
|
||||||
|
| v2 | v3 |
|
||||||
|
| ----------------- | --------------- |
|
||||||
|
| `isOpen` | `open` |
|
||||||
|
| `defaultIsOpen` | `defaultOpen` |
|
||||||
|
| `isDisabled` | `disabled` |
|
||||||
|
| `isInvalid` | `invalid` |
|
||||||
|
| `isRequired` | `required` |
|
||||||
|
| `isReadOnly` | `readOnly` |
|
||||||
|
| `isChecked` | `checked` |
|
||||||
|
| `isLoaded` | `loaded` |
|
||||||
|
| `isIndeterminate` | `indeterminate` |
|
||||||
|
|
||||||
|
### Style and layout props
|
||||||
|
|
||||||
|
| v2 | v3 |
|
||||||
|
| ----------------- | --------------------------- |
|
||||||
|
| `colorScheme` | `colorPalette` |
|
||||||
|
| `noOfLines` | `lineClamp` |
|
||||||
|
| `truncated` | `truncate` |
|
||||||
|
| `spacing` (Stack) | `gap` |
|
||||||
|
| `apply` | `textStyle` or `layerStyle` |
|
||||||
|
|
||||||
|
### Nested style props
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// v2 — sx with nested pseudo-selectors
|
||||||
|
<Box sx={{ "&:hover": { color: "blue.500" } }} />
|
||||||
|
|
||||||
|
// v3 — css prop with "&" selectors
|
||||||
|
<Box css={{ "&:hover": { color: "blue.500" } }} />
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 7 — Component migrations
|
||||||
|
|
||||||
|
### Renamed components
|
||||||
|
|
||||||
|
| v2 | v3 |
|
||||||
|
| ------------- | ----------------------------------- |
|
||||||
|
| `Modal` | `Dialog` |
|
||||||
|
| `FormControl` | `Field` |
|
||||||
|
| `Select` | `NativeSelect` |
|
||||||
|
| `AlertDialog` | `AlertDialog` (compound, see below) |
|
||||||
|
|
||||||
|
`Modal` is the most common rename — every `<Modal>`, `<ModalOverlay>`,
|
||||||
|
`<ModalContent>`, `<ModalHeader>`, `<ModalBody>`, `<ModalFooter>`, and
|
||||||
|
`<ModalCloseButton>` becomes a `Dialog.*` compound part:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// v2
|
||||||
|
<Modal isOpen={open} onClose={onClose}>
|
||||||
|
<ModalOverlay />
|
||||||
|
<ModalContent>
|
||||||
|
<ModalHeader>Title</ModalHeader>
|
||||||
|
<ModalBody>Body</ModalBody>
|
||||||
|
<ModalFooter><Button onClick={onClose}>Close</Button></ModalFooter>
|
||||||
|
</ModalContent>
|
||||||
|
</Modal>
|
||||||
|
|
||||||
|
// v3
|
||||||
|
<Dialog.Root open={open} onOpenChange={({ open }) => setOpen(open)}>
|
||||||
|
<Dialog.Backdrop />
|
||||||
|
<Dialog.Positioner>
|
||||||
|
<Dialog.Content>
|
||||||
|
<Dialog.Header><Dialog.Title>Title</Dialog.Title></Dialog.Header>
|
||||||
|
<Dialog.Body>Body</Dialog.Body>
|
||||||
|
<Dialog.Footer><Button onClick={() => setOpen(false)}>Close</Button></Dialog.Footer>
|
||||||
|
<Dialog.CloseTrigger />
|
||||||
|
</Dialog.Content>
|
||||||
|
</Dialog.Positioner>
|
||||||
|
</Dialog.Root>
|
||||||
|
```
|
||||||
|
|
||||||
|
### Compound component rewrites
|
||||||
|
|
||||||
|
v3 adopts a consistent compound component API. The codemod handles many of
|
||||||
|
these, but complex custom usage needs manual review.
|
||||||
|
|
||||||
|
**Checkbox**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// v2
|
||||||
|
<Checkbox isChecked={val} onChange={fn}>Label</Checkbox>
|
||||||
|
|
||||||
|
// v3
|
||||||
|
<Checkbox.Root checked={val} onCheckedChange={fn}>
|
||||||
|
<Checkbox.Control><Checkbox.Indicator /></Checkbox.Control>
|
||||||
|
<Checkbox.Label>Label</Checkbox.Label>
|
||||||
|
</Checkbox.Root>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Progress**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// v2
|
||||||
|
<Progress value={60} colorScheme="blue" />
|
||||||
|
|
||||||
|
// v3
|
||||||
|
<Progress.Root value={60} colorPalette="blue">
|
||||||
|
<Progress.Track><Progress.Range /></Progress.Track>
|
||||||
|
</Progress.Root>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Accordion**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// v2
|
||||||
|
<Accordion><AccordionItem><AccordionButton /><AccordionPanel /></AccordionItem></Accordion>
|
||||||
|
|
||||||
|
// v3
|
||||||
|
<Accordion.Root>
|
||||||
|
<Accordion.Item value="item-1">
|
||||||
|
<Accordion.ItemTrigger />
|
||||||
|
<Accordion.ItemContent />
|
||||||
|
</Accordion.Item>
|
||||||
|
</Accordion.Root>
|
||||||
|
```
|
||||||
|
|
||||||
|
**FormControl → Field**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// v2
|
||||||
|
<FormControl isInvalid={!!error} isRequired>
|
||||||
|
<FormLabel>Email</FormLabel>
|
||||||
|
<Input type="email" />
|
||||||
|
<FormErrorMessage>{error}</FormErrorMessage>
|
||||||
|
<FormHelperText>We'll never share your email.</FormHelperText>
|
||||||
|
</FormControl>
|
||||||
|
|
||||||
|
// v3
|
||||||
|
<Field.Root invalid={!!error} required>
|
||||||
|
<Field.Label>Email</Field.Label>
|
||||||
|
<Input type="email" />
|
||||||
|
<Field.ErrorText>{error}</Field.ErrorText>
|
||||||
|
<Field.HelpText>We'll never share your email.</Field.HelpText>
|
||||||
|
</Field.Root>
|
||||||
|
```
|
||||||
|
|
||||||
|
All `FormControl` sub-parts map to `Field.*`:
|
||||||
|
|
||||||
|
- `FormLabel` → `Field.Label`
|
||||||
|
- `FormErrorMessage` → `Field.ErrorText`
|
||||||
|
- `FormHelperText` → `Field.HelpText`
|
||||||
|
- `FormControl` props `isInvalid`, `isRequired`, `isDisabled` → `invalid`,
|
||||||
|
`required`, `disabled`
|
||||||
|
|
||||||
|
**Dialog / Drawer / Menu / Tabs** follow the same compound pattern: use
|
||||||
|
`ComponentName.Root`, `.Trigger`, `.Content`, `.Item`, etc. Check the Chakra UI
|
||||||
|
v3 docs for the specific compound API for each.
|
||||||
|
|
||||||
|
### Next.js Image and Link (replacing @chakra-ui/next-js)
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// v2 — @chakra-ui/next-js
|
||||||
|
import { LinkOverlay } from "@chakra-ui/next-js"
|
||||||
|
|
||||||
|
// v3 — asChild pattern
|
||||||
|
import NextLink from "next/link"
|
||||||
|
<ChakraLink asChild><NextLink href="/about">About</NextLink></ChakraLink>
|
||||||
|
|
||||||
|
import NextImage from "next/image"
|
||||||
|
<ChakraImage asChild><NextImage src="..." alt="..." /></ChakraImage>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 8 — Theming migration
|
||||||
|
|
||||||
|
### styleConfig and multiStyleConfig → recipes
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// v3 — single component (recipe)
|
||||||
|
import { defineRecipe } from "@chakra-ui/react"
|
||||||
|
|
||||||
|
// v2
|
||||||
|
const buttonStyle = {
|
||||||
|
baseStyle: { fontWeight: "bold" },
|
||||||
|
variants: { solid: { bg: "blue.500" } },
|
||||||
|
defaultProps: { variant: "solid" },
|
||||||
|
}
|
||||||
|
|
||||||
|
const buttonRecipe = defineRecipe({
|
||||||
|
base: { fontWeight: "bold" },
|
||||||
|
variants: { variant: { solid: { bg: "blue.500" } } },
|
||||||
|
defaultVariants: { variant: "solid" },
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// v3 — slot recipe
|
||||||
|
import { defineSlotRecipe } from "@chakra-ui/react"
|
||||||
|
|
||||||
|
// v2 — multiStyleConfig (multi-part component)
|
||||||
|
const cardStyle = multiStyleConfig({
|
||||||
|
parts: ["root", "header"],
|
||||||
|
baseStyle: { root: { bg: "white" }, header: { fontWeight: "bold" } },
|
||||||
|
})
|
||||||
|
|
||||||
|
const cardSlotRecipe = defineSlotRecipe({
|
||||||
|
slots: ["root", "header"],
|
||||||
|
base: { root: { bg: "white" }, header: { fontWeight: "bold" } },
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
### Typegen for custom tokens
|
||||||
|
|
||||||
|
After adding custom tokens, semantic tokens, recipes, or slot recipes, run
|
||||||
|
typegen to keep TypeScript types in sync:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx @chakra-ui/cli typegen ./theme.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
> **Complex theme migrations** — if you're moving a large v2 theme with many
|
||||||
|
> custom tokens, semantic tokens, or multi-part component styles, use the
|
||||||
|
> `chakra-ui-theming` skill. It covers the full token/recipe/slot-recipe API in
|
||||||
|
> depth and is a better guide than this section alone.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 9 — Next.js specifics
|
||||||
|
|
||||||
|
### App Router
|
||||||
|
|
||||||
|
- Place `<Provider>` in `app/layout.tsx` (Server Component — no `"use client"`)
|
||||||
|
- The generated `components/ui/provider.tsx` already has `"use client"`
|
||||||
|
- Add `suppressHydrationWarning` to `<html>` to prevent color mode flicker
|
||||||
|
- Do not wrap the entire app or layout in `"use client"`
|
||||||
|
|
||||||
|
### Pages Router
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// pages/_app.js
|
||||||
|
import { Provider } from "@/components/ui/provider"
|
||||||
|
|
||||||
|
export default function App({ Component, pageProps }) {
|
||||||
|
return (
|
||||||
|
<Provider>
|
||||||
|
<Component {...pageProps} />
|
||||||
|
</Provider>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Remove any `ColorModeScript` from `pages/_document.tsx` — it is not used in v3.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 10 — Validation checklist
|
||||||
|
|
||||||
|
Work through this after the migration is complete:
|
||||||
|
|
||||||
|
- [ ] Reinstall dependencies: `npm install` / `pnpm install`
|
||||||
|
- [ ] TypeScript: `npx tsc --noEmit` — resolve all type errors
|
||||||
|
- [ ] Lint: `npm run lint`
|
||||||
|
- [ ] Build: `npm run build`
|
||||||
|
- [ ] Visually verify color mode toggle (light ↔ dark)
|
||||||
|
- [ ] Test interactive components: Dialog, Drawer, Menu, Tabs, Accordion
|
||||||
|
- [ ] Test form components: Checkbox, Select/NativeSelect, Input, Radio
|
||||||
|
- [ ] Check for visual regressions across key pages
|
||||||
|
- [ ] Search codebase for leftover v2 imports:
|
||||||
|
```bash
|
||||||
|
grep -r "ColorModeScript\|useColorModeValue\|extendTheme\|styleConfig\|@chakra-ui/icons\|@chakra-ui/next-js" src/
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Clarifying questions (when context is unclear)
|
||||||
|
|
||||||
|
If the user's version, framework, or scope is ambiguous, ask:
|
||||||
|
|
||||||
|
1. "What version of `@chakra-ui/react` are you on right now?"
|
||||||
|
2. "Are you using Next.js App Router, Pages Router, Vite, or plain React?"
|
||||||
|
3. "Are you migrating the full codebase or just specific components?"
|
||||||
|
|
||||||
|
State assumptions clearly if you proceed without asking.
|
||||||
@@ -0,0 +1,284 @@
|
|||||||
|
---
|
||||||
|
name: chakra-ui-refactor
|
||||||
|
description: >
|
||||||
|
Review, convert, and improve UI code using Chakra UI v3. Use this skill
|
||||||
|
whenever a user wants to review Chakra UI code for issues, convert plain
|
||||||
|
HTML/CSS, Tailwind, CSS Modules, or styled-components to Chakra UI, clean up
|
||||||
|
messy Chakra components, fix layout structure or token usage, or asks anything
|
||||||
|
like "is this correct", "what's wrong with this", "review my component",
|
||||||
|
"refactor this", "clean up", "convert", or "chakra-ify this" — even without
|
||||||
|
the words "review" or "refactor". Trigger on any request to check, improve, or
|
||||||
|
convert Chakra UI code, however casually phrased.
|
||||||
|
---
|
||||||
|
|
||||||
|
# Chakra UI Refactor & Review
|
||||||
|
|
||||||
|
You are reviewing and improving UI code using Chakra UI v3. Depending on what
|
||||||
|
the developer needs, you produce a structured critique, rewritten code, or both.
|
||||||
|
Read the code and project context fully before producing any output.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 1 — Orient and determine intent
|
||||||
|
|
||||||
|
Before any output, establish:
|
||||||
|
|
||||||
|
- **Chakra UI version** — check `package.json`; use v3 by default
|
||||||
|
- **Framework** — Next.js App Router, Pages Router, Vite, plain React
|
||||||
|
- **Source type** — existing Chakra, plain HTML/CSS, Tailwind, CSS Modules,
|
||||||
|
styled-components
|
||||||
|
- **What the user is asking:**
|
||||||
|
- **Review only** — "check this", "is this correct/idiomatic", "what's wrong",
|
||||||
|
"review my code" → produce a critique with targeted fixes, no full rewrite
|
||||||
|
- **Refactor / convert** — "refactor this", "convert from Tailwind", "clean
|
||||||
|
this up" → produce rewritten code
|
||||||
|
- **Both** — "review and fix" → critique first, then the rewritten code
|
||||||
|
|
||||||
|
State your reading at the top of the response (e.g. "Reviewing as existing
|
||||||
|
Chakra v3 code. Assuming Next.js App Router.").
|
||||||
|
|
||||||
|
If code isn't shared yet, ask for it. Don't review a description of code.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 2 — Analyze the code
|
||||||
|
|
||||||
|
Work through the code across these dimensions regardless of output mode. For
|
||||||
|
review, they become findings. For refactor, they become the checklist of what to
|
||||||
|
fix.
|
||||||
|
|
||||||
|
**Accessibility**
|
||||||
|
|
||||||
|
- Do all interactive elements have accessible labels? (`aria-label` on icon
|
||||||
|
buttons, `htmlFor`/`id` on label+input pairs, `alt` on images)
|
||||||
|
- Is keyboard navigation possible? (focus rings not suppressed, interactive
|
||||||
|
elements are actually focusable)
|
||||||
|
- Does the heading hierarchy make sense? (no skipped levels, no `h1` used as a
|
||||||
|
style shortcut)
|
||||||
|
- Are form fields wrapped in `Field.Root` with `Field.Label` and
|
||||||
|
`Field.ErrorText`?
|
||||||
|
- Does the component work without color as the only signal?
|
||||||
|
|
||||||
|
**Responsiveness**
|
||||||
|
|
||||||
|
- Do layout components specify behavior at multiple breakpoints?
|
||||||
|
- Are there hardcoded pixel values where responsive tokens would work better?
|
||||||
|
- Would this break on mobile? (fixed widths, `overflow: hidden` on small
|
||||||
|
viewports)
|
||||||
|
|
||||||
|
**Chakra API correctness**
|
||||||
|
|
||||||
|
- Are v3 prop names used? (`disabled` not `isDisabled`, `colorPalette` not
|
||||||
|
`colorScheme`, `gap` not `spacing`, `open` not `isOpen`)
|
||||||
|
- Are compound components used correctly? (`Field.Root`/`Field.Label`,
|
||||||
|
`Dialog.Root`/`Dialog.Content`, etc.)
|
||||||
|
- Is `"use client"` placed correctly in Next.js App Router?
|
||||||
|
- Are there v2 patterns still present? (`extendTheme`, `ColorModeScript`,
|
||||||
|
`useColorModeValue`, `sx` prop)
|
||||||
|
|
||||||
|
**Token and style usage**
|
||||||
|
|
||||||
|
- Are hardcoded colors used where semantic tokens would work? (`bg="#f9fafb"` →
|
||||||
|
`bg="bg.subtle"`)
|
||||||
|
- Are raw hex or palette values used instead of semantic tokens? These won't
|
||||||
|
respect dark mode.
|
||||||
|
- Are there inline `style={{}}` props that should be Chakra style props?
|
||||||
|
|
||||||
|
**Component structure**
|
||||||
|
|
||||||
|
- Is there unnecessary nesting? (`Box > Box > Box` when one would do)
|
||||||
|
- Is manual spacing (`mt={4}` on every child) used where `Stack gap={4}` would
|
||||||
|
be cleaner?
|
||||||
|
- Are the right layout primitives used? (`Flex` vs `Stack` vs `Grid` vs
|
||||||
|
`SimpleGrid`)
|
||||||
|
|
||||||
|
**Maintainability**
|
||||||
|
|
||||||
|
- Does the same visual pattern repeat 3+ times? (candidate for a component or
|
||||||
|
recipe)
|
||||||
|
- Are there one-off style overrides that suggest a recipe or slot recipe?
|
||||||
|
- Are prop types / TypeScript types present and accurate?
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 3a — Review output
|
||||||
|
|
||||||
|
Use this when the user wants a critique, not a rewrite.
|
||||||
|
|
||||||
|
Categorize findings by impact:
|
||||||
|
|
||||||
|
**Critical** — bugs and accessibility failures that break behavior or exclude
|
||||||
|
users
|
||||||
|
|
||||||
|
- Missing `aria-label` on an icon-only button
|
||||||
|
- Form field with no label association
|
||||||
|
- Interactive `Box` with `onClick` but no keyboard access
|
||||||
|
- Wrong v3 prop name that silently does nothing (`isDisabled` doesn't disable in
|
||||||
|
v3)
|
||||||
|
- `"use client"` missing on a component that uses hooks in App Router
|
||||||
|
|
||||||
|
**Improvements** — correctness and quality issues that aren't urgent
|
||||||
|
|
||||||
|
- Hardcoded colors that break dark mode
|
||||||
|
- Missing responsive breakpoints
|
||||||
|
- Unnecessary nesting or wrong layout primitive
|
||||||
|
- v2 patterns that still work but should be updated
|
||||||
|
|
||||||
|
**Optional suggestions** — non-blocking ideas
|
||||||
|
|
||||||
|
- Extract a repeated pattern into a component
|
||||||
|
- Replace a one-off style with a recipe variant
|
||||||
|
- Add a missing TypeScript type
|
||||||
|
|
||||||
|
For each critical issue and significant improvement, show a minimal fix:
|
||||||
|
|
||||||
|
```
|
||||||
|
**Missing aria-label on close button** (Critical)
|
||||||
|
The IconButton for closing the dialog has no accessible label.
|
||||||
|
|
||||||
|
// Before
|
||||||
|
<IconButton icon={<CloseIcon />} onClick={onClose} />
|
||||||
|
// After
|
||||||
|
<IconButton aria-label="Close dialog" icon={<CloseIcon />} onClick={onClose} />
|
||||||
|
```
|
||||||
|
|
||||||
|
Skip sections with nothing to report. Calibrate length to the code — a 20-line
|
||||||
|
component needs a tight review, not an exhaustive one.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 3b — Refactor / convert output
|
||||||
|
|
||||||
|
Use this when the user wants rewritten code.
|
||||||
|
|
||||||
|
### Conversion strategy by source
|
||||||
|
|
||||||
|
**From plain HTML / CSS**
|
||||||
|
|
||||||
|
| HTML | Chakra equivalent |
|
||||||
|
| ------------------------ | ------------------------------------------- |
|
||||||
|
| `<div>` layout wrapper | `Box`, `Flex`, `Stack`, `Grid` |
|
||||||
|
| `<section>`, `<article>` | `Box as="section"`, `Box as="article"` |
|
||||||
|
| `<nav>` | `Box as="nav"` |
|
||||||
|
| `<ul>` / `<li>` | `Box as="ul"` / `Box as="li"`, or `Stack` |
|
||||||
|
| `<button>` | `Button` or `IconButton` |
|
||||||
|
| `<a>` | `Link` |
|
||||||
|
| `<img>` | `Image` (preserve `alt`) |
|
||||||
|
| `<input>`, `<select>` | `Input`, `NativeSelect` inside `Field.Root` |
|
||||||
|
|
||||||
|
| CSS | Chakra style prop |
|
||||||
|
| ------------------------ | ----------------------------- |
|
||||||
|
| `display: flex` | `Flex` or `display="flex"` |
|
||||||
|
| `flex-direction: column` | `Stack` or `flexDir="column"` |
|
||||||
|
| `gap: 16px` | `gap={4}` (1 unit = 4px) |
|
||||||
|
| `padding: 16px 24px` | `py={4} px={6}` |
|
||||||
|
| `border-radius: 8px` | `rounded="md"` |
|
||||||
|
| `color: #6b7280` | `color="fg.muted"` |
|
||||||
|
| `background: #f9fafb` | `bg="bg.subtle"` |
|
||||||
|
|
||||||
|
**From Tailwind CSS**
|
||||||
|
|
||||||
|
| Tailwind | Chakra |
|
||||||
|
| ------------------------------ | ---------------------------------------- |
|
||||||
|
| `flex`, `flex-col`, `flex-row` | `Flex`, `flexDir` |
|
||||||
|
| `gap-4` | `gap={4}` |
|
||||||
|
| `p-4`, `px-6`, `py-2` | `p={4}`, `px={6}`, `py={2}` |
|
||||||
|
| `text-sm`, `font-bold` | `fontSize="sm"`, `fontWeight="bold"` |
|
||||||
|
| `rounded-lg`, `shadow-md` | `rounded="lg"`, `shadow="md"` |
|
||||||
|
| `w-full`, `max-w-lg` | `w="full"`, `maxW="lg"` |
|
||||||
|
| `hidden md:flex` | `display={{ base: "none", md: "flex" }}` |
|
||||||
|
| `grid grid-cols-3` | `SimpleGrid columns={3}` |
|
||||||
|
| `text-gray-500`, `bg-gray-100` | `color="fg.muted"`, `bg="bg.subtle"` |
|
||||||
|
| `hover:bg-gray-100` | `_hover={{ bg: "bg.subtle" }}` |
|
||||||
|
|
||||||
|
Replace Tailwind responsive prefixes with Chakra's breakpoint object syntax:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Tailwind: text-sm md:base lg:text-lg
|
||||||
|
<Text fontSize={{ base: "sm", md: "md", lg: "lg" }} />
|
||||||
|
```
|
||||||
|
|
||||||
|
**From CSS Modules** — convert what you can to Chakra props; keep `className`
|
||||||
|
for styles that can't be expressed as props (animations, complex selectors):
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Before
|
||||||
|
<div className={styles.card}>...</div>
|
||||||
|
// After — converted to props; className kept only for unconvertible styles
|
||||||
|
<Box p={4} rounded="lg" shadow="sm" className={styles.fadeIn}>...</Box>
|
||||||
|
```
|
||||||
|
|
||||||
|
Once all class names are eliminated, remove the import entirely.
|
||||||
|
|
||||||
|
**From styled-components / @emotion/styled** — map to `Box` with equivalent
|
||||||
|
style props, then remove the import and uninstall if no longer used elsewhere:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Before
|
||||||
|
const Card = styled.div`padding: 1rem; &:hover { background: #f3f4f6; }`
|
||||||
|
// After
|
||||||
|
<Box p={4} _hover={{ bg: "bg.muted" }} />
|
||||||
|
```
|
||||||
|
|
||||||
|
**From existing Chakra UI (cleanup)**
|
||||||
|
|
||||||
|
- Flatten `Box > Box > Box` nesting; replace `mt`/`mb` on every child with
|
||||||
|
`Stack gap={N}`
|
||||||
|
- Replace `sx` with `css` (v3 rename); update nested `&:hover` selectors inside
|
||||||
|
it
|
||||||
|
- Replace `bg="gray.50"` → `bg="bg.subtle"` and other semantic token equivalents
|
||||||
|
- Update v2 prop names: `isDisabled→disabled`, `colorScheme→colorPalette`,
|
||||||
|
`spacing→gap`
|
||||||
|
- Update compound components: `FormControl→Field.Root`, `Modal→Dialog`,
|
||||||
|
`Select→NativeSelect`
|
||||||
|
|
||||||
|
### Preserve behavior — non-negotiable
|
||||||
|
|
||||||
|
- Keep all event handlers, state variables, and conditional rendering exactly
|
||||||
|
as-is
|
||||||
|
- Keep `aria-*` attributes; add missing ones where clearly needed
|
||||||
|
- Keep semantic HTML intent (`<nav>` → `Box as="nav"`, not just `Box`)
|
||||||
|
- Keep `"use client"` where it exists; add it only when the component genuinely
|
||||||
|
needs it
|
||||||
|
- Don't add `"use client"` just because a component uses Chakra UI
|
||||||
|
- A partially-converted component that works is better than a fully-converted
|
||||||
|
one that doesn't
|
||||||
|
|
||||||
|
### `asChild` for Next.js Link and Image
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import NextLink from "next/link"
|
||||||
|
<ChakraLink asChild><NextLink href="/about">About</NextLink></ChakraLink>
|
||||||
|
|
||||||
|
import NextImage from "next/image"
|
||||||
|
<ChakraImage asChild><NextImage src="/hero.png" alt="Hero" width={800} height={400} /></ChakraImage>
|
||||||
|
```
|
||||||
|
|
||||||
|
### Refactor output format
|
||||||
|
|
||||||
|
**1. Refactored code** — complete, runnable, with correct imports
|
||||||
|
|
||||||
|
**2. What changed** — concise list focused on non-obvious decisions:
|
||||||
|
|
||||||
|
```
|
||||||
|
- Replaced <div className="flex gap-4"> with <Flex gap={4}>
|
||||||
|
- Replaced bg="#f9fafb" with bg="bg.subtle" for dark mode compatibility
|
||||||
|
- Kept form submit handler and validation logic unchanged
|
||||||
|
- Added aria-label to close icon button (was missing)
|
||||||
|
```
|
||||||
|
|
||||||
|
**3. Suggestions** (optional) — meaningful improvements beyond this refactor:
|
||||||
|
extracting a reusable component, adopting a recipe, migrating a v2 pattern.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## When to ask vs proceed
|
||||||
|
|
||||||
|
Proceed if the code and intent are clear. Ask when:
|
||||||
|
|
||||||
|
- The code isn't shared yet
|
||||||
|
- The component is very large and scope is unclear
|
||||||
|
- There's context or state you can't see that would change the review
|
||||||
|
- There's ambiguous behavior that could be interpreted multiple ways
|
||||||
|
|
||||||
|
State assumptions at the top of the response when you proceed without asking.
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"useTabs": false,
|
||||||
|
"tabWidth": 4,
|
||||||
|
"singleQuote": true,
|
||||||
|
"semi": true
|
||||||
|
}
|
||||||
+32
-26
@@ -1,28 +1,34 @@
|
|||||||
{
|
{
|
||||||
"name": "andrea-slop-fotografie",
|
"name": "andrea-slop-fotografie",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "0.0.0",
|
"version": "0.0.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
"build": "tsc && vite build",
|
"build": "tsc && vite build",
|
||||||
"preview": "vite preview"
|
"preview": "vite preview",
|
||||||
},
|
"typegen": "chakra typegen ./src/theme.ts",
|
||||||
"devDependencies": {
|
"typegen:watch": "chakra typegen ./src/theme.ts --watch"
|
||||||
"@tanstack/router-plugin": "^1.168.40",
|
},
|
||||||
"@types/react": "^19.3.0",
|
"devDependencies": {
|
||||||
"@types/react-dom": "^19.3.0",
|
"@chakra-ui/cli": "^3.37.0",
|
||||||
"typescript": "~6.0.2",
|
"@tanstack/router-plugin": "^1.168.40",
|
||||||
"vite": "^8.3.0"
|
"@types/react": "^19.3.0",
|
||||||
},
|
"@types/react-dom": "^19.3.0",
|
||||||
"dependencies": {
|
"prettier": "^3.9.9",
|
||||||
"@chakra-ui/react": "^3.37.0",
|
"typescript": "~6.0.2",
|
||||||
"@emotion/react": "^11.14.0",
|
"vite": "^8.3.0"
|
||||||
"@tanstack/react-router": "^1.170.39",
|
},
|
||||||
"@tanstack/react-router-devtools": "^1.167.2",
|
"dependencies": {
|
||||||
"@vitejs/plugin-react": "^6.1.1",
|
"@chakra-ui/react": "^3.37.0",
|
||||||
"next-themes": "^0.4.6",
|
"@emotion/react": "^11.14.0",
|
||||||
"react": "^19.3.0",
|
"@fontsource/jost": "^5.3.0",
|
||||||
"react-dom": "^19.3.0"
|
"@fontsource/marcellus": "^5.3.0",
|
||||||
}
|
"@tanstack/react-router": "^1.170.39",
|
||||||
|
"@tanstack/react-router-devtools": "^1.167.2",
|
||||||
|
"@vitejs/plugin-react": "^6.1.1",
|
||||||
|
"next-themes": "^0.4.6",
|
||||||
|
"react": "^19.3.0",
|
||||||
|
"react-dom": "^19.3.0"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Generated
+837
-11
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,2 @@
|
|||||||
|
allowBuilds:
|
||||||
|
esbuild: true
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
{
|
||||||
|
"version": 1,
|
||||||
|
"skills": {
|
||||||
|
"chakra-ui-builder": {
|
||||||
|
"source": "chakra-ui/chakra-ui",
|
||||||
|
"ref": "main",
|
||||||
|
"sourceType": "github",
|
||||||
|
"skillPath": "skills/chakra-ui-builder/SKILL.md",
|
||||||
|
"computedHash": "49bf331b98d9f0ce1634e55c95a83e1cdf394a0b9af0dfd9a5d58fddd3208042"
|
||||||
|
},
|
||||||
|
"chakra-ui-migrate": {
|
||||||
|
"source": "chakra-ui/chakra-ui",
|
||||||
|
"ref": "main",
|
||||||
|
"sourceType": "github",
|
||||||
|
"skillPath": "skills/chakra-ui-migrate/SKILL.md",
|
||||||
|
"computedHash": "8c3da167bac9a2ce018085e1ebc51c4bd3bbcb88313e63eb2873f17db3f0cca2"
|
||||||
|
},
|
||||||
|
"chakra-ui-refactor": {
|
||||||
|
"source": "chakra-ui/chakra-ui",
|
||||||
|
"ref": "main",
|
||||||
|
"sourceType": "github",
|
||||||
|
"skillPath": "skills/chakra-ui-refactor/SKILL.md",
|
||||||
|
"computedHash": "9c6bdd94e0c36455ac4a8623bd3e9e23e357ad8c066fbf3e458fe09ed02668d5"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-1
@@ -24,5 +24,5 @@
|
|||||||
"erasableSyntaxOnly": true,
|
"erasableSyntaxOnly": true,
|
||||||
"noFallthroughCasesInSwitch": true
|
"noFallthroughCasesInSwitch": true
|
||||||
},
|
},
|
||||||
"include": ["src"]
|
"include": ["src", "components"]
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user