chakra-ui-builder

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Chakra 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
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.

若有
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
undefined
bash
undefined

npm

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
undefined
bun add @chakra-ui/react @emotion/react
undefined

Generate snippets with the CLI

使用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:
FrameworkOutput path
Next.js (with
src/
)
src/components/ui/
Next.js (no
src/
)
components/ui/
Vite / plain React
src/components/ui/
Remix
app/components/ui/
bash
npx @chakra-ui/cli snippet add
无参数时,将添加推荐的代码片段集——
provider
toaster
tooltip
,并自动安装所需依赖(包括
next-themes
)。使用
--all
可添加所有代码片段,或先使用
snippet list
浏览可选内容。
CLI会自动检测你的框架,并将文件写入正确路径:
框架输出路径
Next.js(含
src/
src/components/ui/
Next.js(无
src/
components/ui/
Vite / 纯React
src/components/ui/
Remix
app/components/ui/

Wire up the Provider

配置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>,
)
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
可防止
next-themes
注入颜色模式类导致的不匹配问题。请勿在
layout.tsx
中添加
"use client"
——生成的provider文件已包含该指令。
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)

手动配置Provider(当CLI不可用时)

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>
  )
}
若CLI执行失败,请手动创建
components/ui/provider.tsx
,并单独安装
next-themes
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.

  • 组件无样式——应用未被
    <Provider>
    包裹。检查导入路径,确保
    Provider
    包裹了组件树。
  • Hydration不匹配——在App Router的
    <html>
    标签中添加
    suppressHydrationWarning
  • 找不到
    next-themes
    ——安装该依赖:
    npm install next-themes
    (仅手动配置时需要;CLI会自动处理)。
  • extendTheme
    未导出
    ——这是v2模式。在v3中请使用
    createSystem

Step 2 — Choose the right layout primitives

步骤2 — 选择合适的布局原语

Reach for the right Chakra primitive rather than wrapping everything in
Box
:
NeedUse
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.

优先选择合适的Chakra原语,而非用
Box
包裹所有内容:
需求推荐使用
垂直排列元素
Stack
(默认)或
VStack
水平排列元素
HStack
Flex
CSS Grid布局
Grid
+
GridItem
等列网格布局
SimpleGrid columns={N}
居中页面内容
Container maxW="container.lg"
完全控制Flexbox布局带显式属性的
Flex
语义化区块/文章
Box as="section"
/
Box as="article"
避免深层嵌套。若存在三层无语义需求的
Box
嵌套,请简化结构。优先使用
gap
而非外边距来设置兄弟元素间距。

Step 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 (
blue.500
,
gray.100
) only when a specific color is intentional and should not shift with color mode.

Chakra 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.500
gray.100
)。

Step 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
base
(mobile) and
md
(desktop) breakpoints unless the request is explicitly desktop-only.

Chakra采用移动端优先的断点。请统一使用数组或对象语法:
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} />
除非明确要求仅适配桌面端,否则所有布局组件至少应处理
base
(移动端)和
md
(桌面端)断点。

Step 5 — Forms

步骤5 — 表单

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}
.

所有表单字段请使用
Field.Root
——它会正确关联标签、输入框、错误提示和帮助文本:
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>
处理表单提交状态时,请在输入框和按钮上使用
disabled
(而非
isDisabled
)。将相关字段分组放入
Stack 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-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

Chakra的内置组件已自动处理大部分可访问性需求——请勿随意覆盖。你需要手动提供以下内容:
  • 仅含图标按钮:务必添加
    aria-label
    tsx
    <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"

步骤7 — Next.js:何处添加
"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.

在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
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.

当相同结构出现两次以上,或某部分复杂度较高、命名后能让父组件更清晰时,请提取该组件。
当组件存在开发者可能需要定制的有意义样式变体时,推荐使用recipe。当组件包含多个协调部分(如带页眉/正文/页脚的卡片、带标签/数值/图标统计组件等)时,推荐使用slot recipe
对于深度主题定制工作——定义品牌颜色tokens、带明暗模式值的语义tokens、完整的recipe/slot-recipe编写、typegen或导出默认主题,请先阅读
references/theming.md
再回复。该文档涵盖完整的
defineConfig
/
createSystem
API及示例。
对于任何图表请求——条形图、面积图、折线图、饼图/环形图、
BarList
BarSegment
或任何涉及
@chakra-ui/charts
的内容,请先阅读
references/charts.md
再回复。该文档涵盖
useChart
钩子、三种图表类型、Recharts集成、颜色tokens及完整可运行示例。
当你不确定应使用哪个组件,或用户未指定组件时,请阅读
references/component-decision-tree.md
。该文档涵盖所有Chakra组件,并指导如何在相似组件中做出选择。

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"

请生成以下内容:
  1. 完整可运行代码——正确的导入语句,无
    TODO
    ...rest of component
    等占位符
  2. 规范的导入语句——先分组导入Chakra组件,再导入本地组件
  3. 组件拆分——若组件复杂或包含可清晰分离的部分,请拆分为多个组件/文件
  4. 响应式样式——布局至少包含
    base
    md
    断点
  5. 代码后的简要说明——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.
若请求足够清晰,可直接生成有用的代码。在以下情况请先询问用户:
  • 数据结构未知,且会影响整体结构(例如“构建一个表格”——多少列?数据是什么?)
  • 存在用户可能关心的重要设计选择(布局方向、列数、调色板)
  • 用户提及了你未查看过的文件或现有组件
若不确定,请在回复开头说明你的假设,然后进行构建——用户从具体内容调整比从零开始更快。