chakra-ui-builder
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseChakra UI Builder
Chakra UI 开发指南
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.
你将使用Chakra UI v3构建UI,并帮助开发者在他们的项目中配置Chakra UI。你的任务是生成符合项目需求的简洁、可访问、响应式代码,而非通用模板。请先阅读项目上下文,再进行构建或配置。
Step 1 — Read the project context
步骤1 — 阅读项目上下文
Check if available. Look for:
package.json- 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.
若有文件,请查看以下内容:
package.json- Chakra UI版本(默认使用v3模式;仅当明确使用v2时才采用v2模式)
- 框架:Next.js App Router、Pages Router、Vite、纯React
- TypeScript或JavaScript
- 包管理器(从锁文件判断:、
pnpm-lock.yaml、yarn.lock、bun.lock)package-lock.json
若用户提及现有组件,也请浏览相关内容,确保你的代码与已有的命名、文件结构、导入风格等规范保持一致。
若需求模糊,或组件复杂度较高,涉及布局方向、数据结构、调色板、变体数量等关键选择,请先询问用户,再进行构建,避免生成需要废弃的代码。
Project setup
项目配置
If Chakra UI isn't installed yet, complete setup before building.
若尚未安装Chakra UI,请先完成配置再进行构建。
Install
安装
bash
undefinedbash
undefinednpm
npm
npm install @chakra-ui/react @emotion/react
npm install @chakra-ui/react @emotion/react
pnpm
pnpm
pnpm add @chakra-ui/react @emotion/react
pnpm add @chakra-ui/react @emotion/react
yarn
yarn
yarn add @chakra-ui/react @emotion/react
yarn add @chakra-ui/react @emotion/react
bun
bun
bun add @chakra-ui/react @emotion/react
undefinedbun add @chakra-ui/react @emotion/react
undefinedGenerate snippets with the CLI
使用CLI生成代码片段
bash
npx @chakra-ui/cli snippet addWith no arguments this adds the recommended set — , , and
— and automatically installs required dependencies (including
). Use to add every snippet, or to browse
first.
providertoastertooltipnext-themes--allsnippet listThe CLI detects your framework and writes files to the right place:
| Framework | Output path |
|---|---|
Next.js (with | |
Next.js (no | |
| Vite / plain React | |
| Remix | |
bash
npx @chakra-ui/cli snippet add无参数时,将添加推荐的代码片段集——、和,并自动安装所需依赖(包括)。使用可添加所有代码片段,或先使用浏览可选内容。
providertoastertooltipnext-themes--allsnippet listCLI会自动检测你的框架,并将文件写入正确路径:
| 框架 | 输出路径 |
|---|---|
Next.js(含 | |
Next.js(无 | |
| Vite / 纯React | |
| Remix | |
Wire up the Provider
配置Provider
Next.js App Router ():
app/layout.tsxtsx
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>
)
}suppressHydrationWarningnext-themes"use client"layout.tsxNext.js Pages Router ():
pages/_app.tsxtsx
import { Provider } from "@/components/ui/provider"
export default function App({ Component, pageProps }) {
return (
<Provider>
<Component {...pageProps} />
</Provider>
)
}Vite ():
src/main.tsxtsx
import { Provider } from "./components/ui/provider"
createRoot(document.getElementById("root")!).render(
<StrictMode>
<Provider>
<App />
</Provider>
</StrictMode>,
)Next.js App Router():
app/layout.tsxtsx
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>
)
}suppressHydrationWarningnext-themeslayout.tsx"use client"Next.js Pages Router():
pages/_app.tsxtsx
import { Provider } from "@/components/ui/provider"
export default function App({ Component, pageProps }) {
return (
<Provider>
<Component {...pageProps} />
</Provider>
)
}Vite():
src/main.tsxtsx
import { Provider } from "./components/ui/provider"
createRoot(document.getElementById("root")!).render(
<StrictMode>
<Provider>
<App />
</Provider>
</StrictMode>,
)Manual Provider (if CLI is unavailable)
手动配置Provider(当CLI不可用时)
If the CLI fails, create manually and install
separately:
components/ui/provider.tsxnext-themestsx
"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>
)
}若CLI执行失败,请手动创建,并单独安装:
components/ui/provider.tsxnext-themestsx
"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 . Check the import path and that
<Provider>wraps the component tree.Provider - Hydration mismatch — add to
suppressHydrationWarningin App Router.<html> - not found — install it:
next-themes(only needed for the manual fallback; the CLI handles it automatically).npm install next-themes - not exported — this is a v2 pattern. Use
extendThemein v3.createSystem
- 组件无样式——应用未被包裹。检查导入路径,确保
<Provider>包裹了组件树。Provider - Hydration不匹配——在App Router的标签中添加
<html>。suppressHydrationWarning - 找不到——安装该依赖:
next-themes(仅手动配置时需要;CLI会自动处理)。npm install next-themes - 未导出——这是v2模式。在v3中请使用
extendTheme。createSystem
Step 2 — Choose the right layout primitives
步骤2 — 选择合适的布局原语
Reach for the right Chakra primitive rather than wrapping everything in :
Box| Need | Use |
|---|---|
| Vertical stack of items | |
| Horizontal row | |
| CSS Grid | |
| Equal-column grid | |
| Centered page content | |
| Full flexbox control | |
| Semantic section/article | |
Avoid deep nesting. If you're three levels deep with no semantic reason,
flatten it. Prefer over margin between siblings.
Boxgap优先选择合适的Chakra原语,而非用包裹所有内容:
Box| 需求 | 推荐使用 |
|---|---|
| 垂直排列元素 | |
| 水平排列元素 | |
| CSS Grid布局 | |
| 等列网格布局 | |
| 居中页面内容 | |
| 完全控制Flexbox布局 | 带显式属性的 |
| 语义化区块/文章 | |
避免深层嵌套。若存在三层无语义需求的嵌套,请简化结构。优先使用而非外边距来设置兄弟元素间距。
BoxgapStep 3 — Use tokens, not raw values
步骤3 — 使用tokens而非原始值
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 (, ) only when a specific color is
intentional and should not shift with color mode.
blue.500gray.100Chakra v3提供了可自动适配明暗模式的语义tokens。优先使用这些tokens,而非硬编码的调色板值——它们无需额外工作即可让组件支持主题切换。
tsx
// 推荐使用语义tokens
<Box bg="bg.subtle" color="fg.default" borderColor="border.subtle" />
<Text color="fg.muted" />
<Box shadow="md" rounded="lg" />
// 交互组件使用colorPalette(而非colorScheme)
<Button colorPalette="blue">Submit</Button>
<Badge colorPalette="green">Active</Badge>仅当需要固定特定颜色、且该颜色不应随明暗模式变化时,才使用原始调色板值(如、)。
blue.500gray.100Step 4 — Responsive styles
步骤4 — 响应式样式
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 (mobile) and (desktop)
breakpoints unless the request is explicitly desktop-only.
basemdChakra采用移动端优先的断点。请统一使用数组或对象语法:
tsx
// 数组语法:[基础样式, sm, md, lg, xl]
<Box px={[4, 6, 8]} fontSize={["sm", "md", "lg"]} />
// 对象语法:显式指定断点
<SimpleGrid columns={{ base: 1, md: 2, lg: 3 }} gap={6} />
<Stack direction={{ base: "column", md: "row" }} gap={4} />除非明确要求仅适配桌面端,否则所有布局组件至少应处理(移动端)和(桌面端)断点。
basemdStep 5 — Forms
步骤5 — 表单
Use for all form fields — it wires up label, input, error, and help
text correctly:
Field.Roottsx
<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 (not ) on inputs and
buttons. Group related fields in a .
disabledisDisabledStack gap={4}所有表单字段请使用——它会正确关联标签、输入框、错误提示和帮助文本:
Field.Roottsx
<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>处理表单提交状态时,请在输入框和按钮上使用(而非)。将相关字段分组放入中。
disabledisDisabledStack gap={4}Step 6 — Accessibility
步骤6 — 可访问性
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-labeltsx<IconButton aria-label="Close dialog" icon={<CloseIcon />} /> - Images: always pass meaningful text (or
altfor decorative)alt="" - Form labels: use or ensure
Field.Labelmatches the inputhtmlForid - Interactive custom elements: if you build something with on a
onClick, useBoxor an actualas="button"so keyboard navigation works<button> - Semantic headings: use –
h1hierarchy; don't skip levelsh6 - Color contrast: don't use light gray text on white backgrounds; rely on semantic tokens which are contrast-tested
Chakra的内置组件已自动处理大部分可访问性需求——请勿随意覆盖。你需要手动提供以下内容:
- 仅含图标按钮:务必添加
aria-labeltsx<IconButton aria-label="Close dialog" icon={<CloseIcon />} /> - 图片:务必传递有意义的文本(装饰性图片可使用
alt)alt="" - 表单标签:使用,或确保
Field.Label与输入框的htmlFor匹配id - 自定义交互元素:若在上使用
Box,请使用onClick或实际的as="button"标签,以支持键盘导航<button> - 语义化标题:使用–
h1层级,请勿跳过层级h6 - 颜色对比度:请勿在白色背景上使用浅灰色文本;依赖经过对比度测试的语义tokens
Step 7 — Next.js: where to add "use client"
"use client"步骤7 — Next.js:何处添加"use client"
"use client"In Next.js App Router, Server Components are the default. Add
only to files that need it — not to entire layouts or pages.
"use client"A component needs when it:
"use client"- Uses React hooks (,
useState,useEffect, etc.)useContext - Handles browser events (with state, form submission, etc.)
onClick - 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.
在Next.js App Router中,默认使用服务器组件(Server Components)。仅在需要时才添加——不要将其添加到整个布局或页面中。
"use client"当组件满足以下条件时,需要:
"use client"- 使用React钩子(、
useState、useEffect等)useContext - 处理浏览器事件(带状态的、表单提交等)
onClick - 使用浏览器API
tsx
// 服务器组件——无需指令
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>
)
}
// 客户端组件——需要指令
;("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>
)
}目标是将交互逻辑推到组件树的叶子节点——尽可能让更多组件保持为服务器组件。
Step 8 — When to extract components, use recipes, and customize the theme
步骤8 — 何时提取组件、使用recipes及定制主题
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 before responding. It covers the complete
/ API with full examples.
references/theming.mddefineConfigcreateSystemFor any chart request — bar charts, area charts, line charts, pie/donut charts,
, , or anything involving — read
before responding. It covers the hook, all
three chart types, Recharts integration, color tokens, and complete runnable
examples.
BarListBarSegment@chakra-ui/chartsreferences/charts.mduseChartWhen you're unsure which component to use, or the user hasn't specified one,
read . It covers every Chakra component
with guidance on when to choose one over a similar alternative.
references/component-decision-tree.md当相同结构出现两次以上,或某部分复杂度较高、命名后能让父组件更清晰时,请提取该组件。
当组件存在开发者可能需要定制的有意义样式变体时,推荐使用recipe。当组件包含多个协调部分(如带页眉/正文/页脚的卡片、带标签/数值/图标统计组件等)时,推荐使用slot recipe。
对于深度主题定制工作——定义品牌颜色tokens、带明暗模式值的语义tokens、完整的recipe/slot-recipe编写、typegen或导出默认主题,请先阅读再回复。该文档涵盖完整的/ API及示例。
references/theming.mddefineConfigcreateSystem对于任何图表请求——条形图、面积图、折线图、饼图/环形图、、或任何涉及的内容,请先阅读再回复。该文档涵盖钩子、三种图表类型、Recharts集成、颜色tokens及完整可运行示例。
BarListBarSegment@chakra-ui/chartsreferences/charts.mduseChart当你不确定应使用哪个组件,或用户未指定组件时,请阅读。该文档涵盖所有Chakra组件,并指导如何在相似组件中做出选择。
references/component-decision-tree.mdOutput format
输出格式
Produce:
- Complete, runnable code — correct imports, no placeholders like or
TODO...rest of component - Proper import statements — group Chakra imports, then local imports
- Component separation — split into multiple components/files if the component is complex or contains clearly separable parts
- Responsive styles — at minimum and
basebreakpoints for layoutmd - 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"请生成以下内容:
- 完整可运行代码——正确的导入语句,无或
TODO等占位符...rest of component - 规范的导入语句——先分组导入Chakra组件,再导入本地组件
- 组件拆分——若组件复杂或包含可清晰分离的部分,请拆分为多个组件/文件
- 响应式样式——布局至少包含和
base断点md - 代码后的简要说明——2-4句话说明关键决策(布局方案、可访问性选择、响应式策略)。若请求较为简单,可省略说明。
tsx
// 良好的导入风格
import { Box, Button, Field, Stack, Text } from "@chakra-ui/react"
// 然后导入本地组件
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.
若请求足够清晰,可直接生成有用的代码。在以下情况请先询问用户:
- 数据结构未知,且会影响整体结构(例如“构建一个表格”——多少列?数据是什么?)
- 存在用户可能关心的重要设计选择(布局方向、列数、调色板)
- 用户提及了你未查看过的文件或现有组件
若不确定,请在回复开头说明你的假设,然后进行构建——用户从具体内容调整比从零开始更快。