Technical Documentation: gpbl/UI
ℹ️ Provenance: Multi-Tier Ingestion · CodeWiki Reference
Overview (`README.md`)
shadcn/ui
A set of beautifully designed components that you can customize, extend, and build on. Start here then make it your own. Open Source. Open Code. Use this to build your own component library.
Documentation
Visit https://ui.shadcn.com/docs to view the documentation.
Contributing
Please read the contributing guide.
License
Licensed under the MIT license.
Overview (`.changeset/README.md`)
Changesets
Hello and welcome! This folder has been automatically generated by @changesets/cli, a build tool that works
with multi-package repos, or single-package repos to help you version and publish your code. You can
find the full documentation for it in our repository
We have a quick list of common questions to get you started engaging with this project in
our documentation
Overview (`apps/v4/README.md`)
This is a wip registry for the shadcn canary version. It has React 19 and Tailwind v4 components.
Overview (`packages/shadcn/README.md`)
shadcn
A CLI for adding components to your project.
create
Use the create command to create a new project. You will be taken to a website to build your custom design system and choose your framework.
npx shadcn createinit
Use the init command to initialize dependencies for a new project.
The init command installs dependencies, adds the cn util, configures Tailwind CSS, and CSS variables for the project.
npx shadcn initapply
Use the apply command to apply a preset to an existing project.
The apply command overwrites the current preset configuration, reinstalls detected UI components, and updates fonts and CSS variables to match the new preset.
npx shadcn apply --preset a2r6bwadd
Use the add command to add components to your project.
The add command adds a component to your project and installs all required dependencies.
npx shadcn add [component]Example
npx shadcn add alert-dialogYou can also run the command without any arguments to view a list of all available components:
npx shadcn addDocumentation
Visit https://ui.shadcn.com/docs/cli to view the documentation.
License
Licensed under the MIT license.
Overview (`packages/tests/README.md`)
Tests
This package contains integration tests that verify the shadcn CLI works correctly with a local registry. The tests run actual CLI commands against test fixtures to ensure files are created and updated properly.
Running Tests
Run the following command from the root of the workspace:
pnpm tests:testWriting Tests
import {
createFixtureTestDirectory,
fileExists,
npxShadcn,
} from "../utils/helpers"
describe("my test suite", () => {
it("should do something", async () => {
// Create a test directory from a fixture
const testDir = await createFixtureTestDirectory("next-app")
// Run CLI command
await npxShadcn(testDir, ["init", "--base-color=neutral"])
// Make assertions
expect(await fileExists(path.join(testDir, "components.json"))).toBe(true)
})
})Overview (`templates/astro-app/README.md`)
Astro + React + TypeScript + shadcn/ui
This is a template for a new Astro project with React, TypeScript, and shadcn/ui.
Adding components
To add components to your app, run the following command:
npx shadcn@latest add buttonThis will place the ui components in the src/components directory.
Using components
To use the components in your app, import them in an .astro file:
---
import { Button } from "@/components/ui/button"
---
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Astro App</title>
</head>
<body>
<div class="grid h-screen place-items-center content-center">
<Button>Button</Button>
</div>
</body>
</html>Overview (`templates/astro-monorepo/README.md`)
Astro + React + TypeScript + shadcn/ui (Monorepo)
This is a monorepo template for Astro with React, TypeScript, and shadcn/ui.
Structure
apps/web- Astro applicationpackages/ui- Shared UI components (shadcn/ui)
Adding components
To add components, run the following command from the root:
npx shadcn@latest add button -c apps/webUsing components
To use the components in your app, import them in an .astro file:
---
import { Button } from "@workspace/ui/components/button"
---
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Astro App</title>
</head>
<body>
<div class="grid h-screen place-items-center content-center">
<Button>Button</Button>
</div>
</body>
</html>Overview (`templates/next-app/README.md`)
Next.js template
This is a Next.js template with shadcn/ui.
Adding components
To add components to your app, run the following command:
npx shadcn@latest add buttonThis will place the ui components in the components directory.
Using components
To use the components in your app, import them as follows:
import { Button } from "@/components/ui/button";Overview (`templates/next-monorepo/README.md`)
shadcn/ui monorepo template
This is a Next.js monorepo template with shadcn/ui.
Adding components
To add components to your app, run the following command at the root of your web app:
pnpm dlx shadcn@latest add button -c apps/webThis will place the ui components in the packages/ui/src/components directory.
Using components
To use the components in your app, import them from the ui package.
import { Button } from "@workspace/ui/components/button";Overview (`templates/react-router-app/README.md`)
React Router + shadcn/ui
This is a template for a new React Router project with React, TypeScript, and shadcn/ui.
Adding components
To add components to your app, run the following command:
npx shadcn@latest add buttonThis will place the ui components in the components directory.
Using components
To use the components in your app, import them as follows:
import { Button } from "@/components/ui/button";Overview (`templates/react-router-monorepo/README.md`)
shadcn/ui monorepo template
This is a React Router monorepo template with shadcn/ui.
Adding components
To add components to your app, run the following command at the root of your web app:
pnpm dlx shadcn@latest add button -c apps/webThis will place the ui components in the packages/ui/src/components directory.
Using components
To use the components in your app, import them from the ui package.
import { Button } from "@workspace/ui/components/button";Overview (`templates/start-app/README.md`)
TanStack Start + shadcn/ui
This is a template for a new TanStack Start project with React, TypeScript, and shadcn/ui.
Adding components
To add components to your app, run the following command:
npx shadcn@latest add buttonThis will place the ui components in the components directory.
Using components
To use the components in your app, import them as follows:
import { Button } from "@/components/ui/button";Overview (`templates/start-monorepo/README.md`)
shadcn/ui monorepo template
This is a TanStack Start monorepo template with shadcn/ui.
Adding components
To add components to your app, run the following command at the root of your web app:
pnpm dlx shadcn@latest add button -c apps/webThis will place the ui components in the packages/ui/src/components directory.
Using components
To use the components in your app, import them from the ui package.
import { Button } from "@workspace/ui/components/button";Overview (`templates/vite-app/README.md`)
React + TypeScript + Vite + shadcn/ui
This is a template for a new Vite project with React, TypeScript, and shadcn/ui.
Adding components
To add components to your app, run the following command:
npx shadcn@latest add buttonThis will place the ui components in the src/components directory.
Using components
To use the components in your app, import them as follows:
import { Button } from "@/components/ui/button"Overview (`templates/vite-monorepo/README.md`)
shadcn/ui monorepo template
This is a Vite monorepo template with shadcn/ui.
Adding components
To add components to your app, run the following command at the root of your web app:
pnpm dlx shadcn@latest add button -c apps/webThis will place the ui components in the packages/ui/src/components directory.
Using components
To use the components in your app, import them from the ui package.
import { Button } from "@workspace/ui/components/button";Overview (`apps/v4/examples/README.md`)
Examples
This directory contains demo components for the component documentation.
Directory Structure
examples
├── base
│ ├── button-demo.tsx
│ └── ...
├── radix
│ └── ...
└── __index__.tsx # Auto-generated by registry:buildAdding a New Example
- Create a new
.tsxfile inexamples/baseorexamples/radix:
// examples/base/button-loading.tsx
import { Button } from "@/styles/base-nova/ui/button"
export function ButtonLoading() {
return <Button disabled>Loading...</Button>
}- Run the registry build to regenerate the index:
pnpm --filter=v4 registry:build- Use the example in documentation by referencing its name (filename without
.tsx):
<ComponentPreview name="button-loading" />Notes
- Example files should be placed directly in
examples/baseorexamples/radix, not in subdirectories. - Base examples should import from
@/styles/base-nova/*. Radix examples should import from@/styles/radix-nova/*. - Both named exports and default exports are supported.
- After adding or removing examples, run
pnpm --filter=v4 registry:buildto update the index.
Overview (`apps/v4/registry/bases/README.md`)
Registry bases (`base` and `radix`)
This folder holds two parallel registries:
base/— Base UI–backed components and blocksradix/— Radix-backed components and blocks
Keep them in sync
For any shared surface (same preview block, same card, same example intent), changes should be applied to both base and radix variants.
- Adjust only what must differ: imports (
.../base/ui/...vs.../radix/ui/...) and primitive APIs. - Avoid editing only one tree unless the work is intentionally scoped to a single base.
Project automation: see .cursor/rules/registry-bases-parity.mdc for the Cursor rule agents use when working under apps/v4/registry/bases/.
Overview (`templates/next-monorepo/packages/eslint-config/README.md`)
`@workspace/eslint-config`
Shared eslint configuration for the workspace.
Overview (`templates/next-monorepo/packages/typescript-config/README.md`)
`@workspace/typescript-config`
Shared typescript configuration for the workspace.
Apps V4 Content Docs (Root) Index (`apps/v4/content/docs/(root)/index.mdx`)
title: Introduction
This is not a component library. It is how you build your component library.
You know how most traditional component libraries work: you install a package from NPM, import the components, and use them in your app.
This approach works well until you need to customize a component to fit your design system or require one that isn’t included in the library. Often, you end up wrapping library components, writing workarounds to override styles, or mixing components from different libraries with incompatible APIs.
This is what shadcn/ui aims to solve. It is built around the following principles:
- Open Code: The top layer of your component code is open for modification.
- Composition: Every component uses a common, composable interface, making them predictable.
- Distribution: A flat-file schema and command-line tool make it easy to distribute components.
- Beautiful Defaults: Carefully chosen default styles, so you get great design out-of-the-box.
- AI-Ready: Open code for LLMs to read, understand, and improve.
Open Code
shadcn/ui hands you the actual component code. You have full control to customize and extend the components to your needs. This means:
- Full Transparency: You see exactly how each component is built.
- Easy Customization: Modify any part of a component to fit your design and functionality requirements.
- AI Integration: Access to the code makes it straightforward for LLMs to read, understand, and even improve your components.
In a typical library, if you need to change a button’s behavior, you have to override styles or wrap the component. With shadcn/ui, you simply edit the button code directly.
shadcn/ui follows a headless component architecture. This means the core
of your app can receive fixes by updating your dependencies, for
instance, radix-ui or input-otp.
The topmost layer, i.e., the one closest to your design system, is not
coupled with the implementation of the library. It stays open for
modification.
</AccordionContent>Composition
Every component in shadcn/ui shares a common, composable interface. If a component does not exist, we bring it in, make it composable, and adjust its style to match and work with the rest of the design system.
A shared, composable interface means it's predictable for both your team and LLMs. You are not learning different APIs for every new component. Even for third-party ones.
Distribution
shadcn/ui is also a code distribution system. It defines a schema for components and a CLI to distribute them.
- Schema: A flat-file structure that defines the components, their dependencies, and properties.
- CLI: A command-line tool to distribute and install components across projects with cross-framework support.
You can use the schema to distribute your components to other projects or have AI generate completely new components based on existing schema.
Beautiful Defaults
shadcn/ui comes with a large collection of components that have carefully chosen default styles. They are designed to look good on their own and to work well together as a consistent system:
- Good Out-of-the-Box: Your UI has a clean and minimal look without extra work.
- Unified Design: Components naturally fit with one another. Each component is built to match the others, keeping your UI consistent.
- Easily Customizable: If you want to change something, it's simple to override and extend the defaults.
AI-Ready
The design of shadcn/ui makes it easy for AI tools to work with your code. Its open code and consistent API allow AI models to read, understand, and even generate new components.
An AI model can learn how your components work and suggest improvements or even create new components that integrate with your existing design.
Apps V4 Content Docs Changelog 2025 09 Registry Index (`apps/v4/content/docs/changelog/2025-09-registry-index.mdx`)
title: September 2025 - Registry Index date: 2025-09-02
We've created an index of open source registries that you can install items from.
You can search, view and add items from the registry index without configuring the components.json file.
They'll be automatically added to your components.json file for you.
npx shadcn add @ai-elements/prompt-inputThe full list of registries is available at https://ui.shadcn.com/r/registries.json.
To add a registry to the index, submit a PR to the shadcn/ui repository. See the registry index documentation for more details.
Apps V4 Content Docs Changelog Index (`apps/v4/content/docs/changelog/index.mdx`)
title: Changelog
Latest updates and announcements for shadcn/ui.
Apps V4 Content Docs Components Index (`apps/v4/content/docs/components/index.mdx`)
title: Components
Can't find what you need? Try the registry directory for community-maintained components.
Apps V4 Content Docs Dark Mode Index (`apps/v4/content/docs/dark-mode/index.mdx`)
title: Dark Mode
Apps V4 Content Docs Forms Index (`apps/v4/content/docs/forms/index.mdx`)
title: Forms
import { ClipboardListIcon } from "lucide-react"
Pick Your Framework
Start by selecting your framework. Then follow the instructions to learn how to build forms with shadcn/ui and the form library of your choice.
Apps V4 Content Docs Installation Index (`apps/v4/content/docs/installation/index.mdx`)
title: Installation
Recommended for new projects: Use shadcn/create to build your preset visually and generate the right setup command for your framework.
Choose the setup that matches your starting point.
<LinkedCard
href="#use-create"
className="items-start gap-1 p-6 text-sm md:p-6"
Use shadcn/create
Build your preset visually and generate a setup command.Scaffold a supported template directly from the terminal.Add shadcn/ui to an app you already created.Use shadcn/create
Build your preset visually, preview your choices, and generate a framework-specific setup command.
Open shadcn/createAvailable for Next.js, Vite, Laravel, React Router, Astro, and TanStack Start.
Use the CLI
Use the CLI to scaffold a new project directly from the terminal:
npx shadcn@latest init -t [framework]Supported templates: next, vite, start, react-router, and astro.
For Laravel, create the app first with laravel new, then run npx shadcn@latest init.
Existing Project
Each framework guide includes an Existing Project section with the manual setup steps for that framework.
Pick your framework below and follow that path.
Choose Your Framework
For Laravel, start with laravel new before using shadcn/create or shadcn init.
Apps V4 Content Docs Registry Getting Started (`apps/v4/content/docs/registry/getting-started.mdx`)
title: Getting Started
This guide will walk you through the process of setting up your own component registry. It assumes you already have a project with components and would like to turn it into a registry.
If you're starting a new registry project, you can use the registry template as a starting point. We have already configured it for you.
Requirements
You are free to design and host your custom registry as you see fit. The only requirement is that your registry items must be valid JSON files that conform to the registry-item schema specification.
If you'd like to see an example of a registry, we have a template project for you to use as a starting point.
registry.json
The registry.json is the entry point for the registry. It contains the registry's name, homepage, and defines all the items present in the registry.
Your registry must have this file (or JSON payload) present at the root of the registry endpoint. The registry endpoint is the URL where your registry is hosted.
The shadcn CLI will automatically generate this file for you when you run the build command.
Add a registry.json file
Create a registry.json file in the root of your project. Your project can be a Next.js, Vite, Vue, Svelte, PHP or any other framework as long as it supports serving JSON over HTTP.
{
"$schema": "https://ui.shadcn.com/schema/registry.json",
"name": "acme",
"homepage": "https://acme.com",
"items": [
// ...
]
}This registry.json file must conform to the registry schema specification.
Add a registry item
Create your component
Add your first component. Here's an example of a simple <HelloWorld /> component:
import { Button } from "@/components/ui/button"
export function HelloWorld() {
return <Button>Hello World</Button>
}registry
└── new-york
└── hello-world
└── hello-world.tsxAdd your component to the registry
To add your component to the registry, you need to add your component definition to registry.json.
{
"$schema": "https://ui.shadcn.com/schema/registry.json",
"name": "acme",
"homepage": "https://acme.com",
"items": [
{
"name": "hello-world",
"type": "registry:block",
"title": "Hello World",
"description": "A simple hello world component.",
"files": [
{
"path": "registry/new-york/hello-world/hello-world.tsx",
"type": "registry:component"
}
]
}
]
}You define your registry item by adding a name, type, title, description and files.
For every file you add, you must specify the path and type of the file. The path is the relative path to the file from the root of your project. The type is the type of the file.
You can read more about the registry item schema and file types in the registry item schema docs.
Build your registry
Install the shadcn CLI
npm install shadcn@latestAdd a build script
Add a registry:build script to your package.json file.
{
"scripts": {
"registry:build": "shadcn build"
}
}Run the build script
Run the build script to generate the registry JSON files.
npm run registry:buildYou can change the output directory by passing the --output option. See the shadcn build command for more information.
Serve your registry
If you're running your registry on Next.js, you can now serve your registry by running the next server. The command might differ for other frameworks.
npm run devYour files will now be served at http://localhost:3000/r/[NAME].json eg. http://localhost:3000/r/hello-world.json.
Publish your registry
To make your registry available to other developers, you can publish it by deploying your project to a public URL.
Guidelines
Here are some guidelines to follow when building components for a registry.
- Place your registry item in the
registry/[STYLE]/[NAME]directory. I'm usingnew-yorkas an example. It can be anything you want as long as it's nested under theregistrydirectory. - The following properties are required for the block definition:
name,description,typeandfiles. - It is recommended to add a proper name and description to your registry item. This helps LLMs understand the component and its purpose.
- Make sure to list all registry dependencies in
registryDependencies. A registry dependency is the name of the component in the registry eg.input,button,card, etc or a URL to a registry item eg.http://localhost:3000/r/editor.json. - Make sure to list all dependencies in
dependencies. A dependency is the name of the package in the registry eg.zod,sonner, etc. To set a version, you can use thename@versionformat eg.zod@^3.20.0. - Imports should always use the
@/registrypath. eg.import { HelloWorld } from "@/registry/new-york/hello-world/hello-world" - Ideally, place your files within a registry item in
components,hooks,libdirectories.
Install using the CLI
To install a registry item using the shadcn CLI, use the add command followed by the URL of the registry item.
npx shadcn@latest add http://localhost:3000/r/hello-world.jsonSee the Namespaced
Registries docs for more information on
how to install registry items from a namespaced registry.
Apps V4 Content Docs Registry Index (`apps/v4/content/docs/registry/index.mdx`)
title: Introduction
You can use the shadcn CLI to run your own code registry. Running your own registry allows you to distribute your custom components, hooks, pages, config, rules and other files to any project.
Ready to create your own registry? In the next section, we'll walk you through setting up your own custom registry step-by-step, from creating your first component to publishing it for others to use.
Set up and build your own registry<LinkedCard
href="/docs/registry/authentication"
className="items-start text-sm md:p-6"
Authentication
Secure your registry with authenticationConfigure registries with namespacesRegistry item examples and configurationsSchema specification for registry.jsonApps V4 Content Docs Registry Registry Index (`apps/v4/content/docs/registry/registry-index.mdx`)
title: Add a Registry
The open source registry index is a list of all the open source registries that are available to use out of the box.
When you run shadcn add or shadcn search, the CLI will automatically check the registry index for the registry you are looking for and add it to your components.json file.
You can see the full list at https://ui.shadcn.com/r/registries.json.
Adding a Registry
- Add your registry to
apps/v4/registry/directory.json - Run
pnpm registry:buildto updateregistries.jsonfile. - Create a pull request to https://github.com/shadcn-ui/ui
Once you have submitted your request, it will be validated and reviewed by the team.
Requirements
- The registry must be open source and publicly accessible.
- The registry must be a valid JSON file that conforms to the registry schema specification.
- The registry is expected to be a flat registry with no nested items i.e
/registry.jsonand/component-name.jsonfiles are expected to be in the root of the registry. - The
filesarray, if present, must NOT include acontentproperty.
Here's an example of a valid registry:
{
"$schema": "https://ui.shadcn.com/schema/registry.json",
"name": "acme",
"homepage": "https://acme.com",
"items": [
{
"name": "login-form",
"type": "registry:component",
"title": "Login Form",
"description": "A login form component.",
"files": [
{
"path": "registry/new-york/auth/login-form.tsx",
"type": "registry:component"
}
]
},
{
"name": "example-login-form",
"type": "registry:component",
"title": "Example Login Form",
"description": "An example showing how to use the login form component.",
"files": [
{
"path": "registry/new-york/examples/example-login-form.tsx",
"type": "registry:component"
}
]
}
]
}Apps V4 Content Docs Rtl Index (`apps/v4/content/docs/rtl/index.mdx`)
title: "RTL"
shadcn/ui components have first-class support for right-to-left (RTL) layouts. Text alignment, positioning, and directional styles automatically adapt for languages like Arabic, Hebrew, and Persian.
When you install components, the CLI automatically transforms physical positioning classes to logical equivalents, so your components work seamlessly in both LTR and RTL contexts.
Get Started
Select your framework to get started with RTL support.
How it works
When you add components with rtl: true set in your components.json, the shadcn CLI automatically transforms classes and props to be RTL compatible:
- Physical positioning classes like
left-*andright-*are converted to logical equivalents likestart-*andend-*. - Directional props are updated to use logical values.
- Text alignment and spacing classes are adjusted accordingly.
- Supported icons are automatically flipped using
rtl:rotate-180.
Try it out
Click the link below to open a Next.js project with RTL support in v0.
Supported Styles
Automatic RTL transformation via the CLI is only available for projects created using shadcn create with the new styles (base-nova, radix-nova, etc.).
For other styles, see the Migration Guide.
Font Recommendations
For the best RTL experience, we recommend using fonts that have proper support for your target language. Noto is a great font family for this and it pairs well with Inter and Geist.
See your framework's RTL guide under Get Started for details on installing and configuring RTL fonts.
Animations
The CLI also handles animation classes, automatically transforming physical directional animations to their logical equivalents. For example, slide-in-from-right becomes slide-in-from-end.
This ensures animations like dropdowns, popovers, and tooltips animate in the correct direction based on the document's text direction.
A note on tw-animate-css:
There is a known issue with the tw-animate-css library where the logical slide utilities are not working as expected. For now, make sure you pass in the dir prop to portal elements.
<Popover>
<PopoverTrigger>Open</PopoverTrigger>
<PopoverContent dir="rtl">
<div>Content</div>
</PopoverContent>
</Popover><Tooltip>
<TooltipTrigger>Open</TooltipTrigger>
<TooltipContent dir="rtl">
<div>Content</div>
</TooltipContent>
</Tooltip>Migrating existing components
If you have existing components installed before enabling RTL, you can migrate them using the CLI as follows:
npx shadcn@latest migrate rtl [path][path] accepts a path or glob pattern to migrate. If you don't provide a path, it will migrate all the files in the ui directory.
Manual Migration (Optional)
The following components are not automatically migrated by the CLI. Follow the RTL support section for each component to manually migrate them.
Migrate Icons
Some icons like ArrowRightIcon or ChevronLeftIcon might need the rtl:rotate-180 class to be flipped correctly. Add the rtl:rotate-180 class to the icon component to flip it correctly.
<ArrowRightIcon className="rtl:rotate-180" />Add direction component
Add the direction component to your project.
npx shadcn@latest add directionAdd DirectionProvider
Follow your framework's documentation for details on how to add the DirectionProvider component to your project.
See the Get Started section for details on how to add the DirectionProvider component to your project.
Apps V4 Content Docs Meta.Json (`apps/v4/content/docs/meta.json`)
{
"root": true,
"pages": [
"components",
"(root)",
"changelog",
"forms",
"installation",
"dark-mode",
"rtl",
"registry"
]
}
Apps V4 Content Docs (Root) Blocks (`apps/v4/content/docs/(root)/_blocks.mdx`)
title: Blocks
We are inviting the community to contribute to the blocks library. Share your components and blocks with other developers and help build a library of high-quality, reusable components.
We'd love to see all types of blocks: applications, marketing, products, and more.
Setup your workspace
Fork the repository
git clone https://github.com/shadcn-ui/ui.gitCreate a new branch
git checkout -b username/my-new-blockInstall dependencies
pnpm installStart the dev server
pnpm www:devAdd a block
A block can be a single component (eg. a variation of a ui component) or a complex component (eg. a dashboard) with multiple components, hooks, and utils.
Create a new block
Create a new folder in the apps/www/registry/new-york/blocks directory. Make sure the folder is named in kebab-case and under new-york.
apps
└── www
└── registry
└── new-york
└── blocks
└── dashboard-01Note: The build script will take care of building the block for the default style.
Add your block files
Add your files to the block folder. Here is an example of a block with a page, components, hooks, and utils.
dashboard-01
└── page.tsx
└── components
└── hello-world.tsx
└── example-card.tsx
└── hooks
└── use-hello-world.ts
└── lib
└── format-date.tsNote: You can start with one file and add more files later.
Add your block to the registry
Add your block definition to `registry-blocks.tsx`
To add your block to the registry, you need to add your block definition to registry-blocks.ts.
This follows the registry schema at https://ui.shadcn.com/schema/registry-item.json.
export const blocks = [
// ...
{
name: "dashboard-01",
author: "shadcn (https://ui.shadcn.com)",
title: "Dashboard",
description: "A simple dashboard with a hello world component.",
type: "registry:block",
registryDependencies: ["input", "button", "card"],
dependencies: ["zod"],
files: [
{
path: "blocks/dashboard-01/page.tsx",
type: "registry:page",
target: "app/dashboard/page.tsx",
},
{
path: "blocks/dashboard-01/components/hello-world.tsx",
type: "registry:component",
},
{
path: "blocks/dashboard-01/components/example-card.tsx",
type: "registry:component",
},
{
path: "blocks/dashboard-01/hooks/use-hello-world.ts",
type: "registry:hook",
},
{
path: "blocks/dashboard-01/lib/format-date.ts",
type: "registry:lib",
},
],
categories: ["dashboard"],
},
]Make sure you add a name, description, type, registryDependencies, dependencies, files, and categories. We'll go over each of these in more detail in the schema docs (coming soon).
Run the build script
pnpm registry:buildNote: you do not need to run this script for every change. You only need to run it when you update the block definition.
View your block
Once the build script is finished, you can view your block at http://localhost:3333/blocks/[CATEGORY] or a full screen preview at http://localhost:3333/view/styles/new-york/dashboard-01.
Build your block
You can now build your block by editing the files in the block folder and viewing the changes in the browser.
If you add more files, make sure to add them to the files array in the block definition.
Publish your block
Once you're ready to publish your block, you can submit a pull request to the main repository.
Run the build script
pnpm registry:buildCapture a screenshot
pnpm registry:captureNote: If you've run the capture script before, you might need to delete the existing screenshots (both light and dark) at apps/www/public/r/styles/new-york and run the script again.
Submit a pull request
Commit your changes and submit a pull request to the main repository.
Your block will be reviewed and merged. Once merged it will be published to the website and available to be installed via the CLI.
Categories
The categories property is used to organize your block in the registry.
Add a category
If you need to add a new category, you can do so by adding it to the registryCategories array in apps/www/registry/registry-categories.ts.
export const registryCategories = [
// ...
{
name: "Input",
slug: "input",
hidden: false,
},
]Guidelines
Here are some guidelines to follow when contributing to the blocks library.
- The following properties are required for the block definition:
name,description,type,files, andcategories. - Make sure to list all registry dependencies in
registryDependencies. A registry dependency is the name of the component in the registry eg.input,button,card, etc. - Make sure to list all dependencies in
dependencies. A dependency is the name of the package in the registry eg.zod,sonner, etc. - If your block has a page (optional), it should be the first entry in the
filesarray and it should have atargetproperty. This helps the CLI place the page in the correct location for file-based routing. - Imports should always use the
@/registrypath. eg.import { Input } from "@/registry/new-york/input"
Apps V4 Content Docs (Root) Cli (`apps/v4/content/docs/(root)/cli.mdx`)
title: shadcn
init
Use the init command to initialize configuration and dependencies for an existing project, or create a new project with --name.
The init command installs dependencies, adds the cn util and configures CSS variables for the project.
npx shadcn@latest initOptions
Usage: shadcn init [options] [components...]
initialize your project and install dependencies
Arguments:
components names, url or local path to component
Options:
-t, --template <template> the template to use. (next, vite, start, react-router, laravel, astro)
-b, --base <base> the component library to use. (radix, base)
-p, --preset [name] use a preset configuration
-y, --yes skip confirmation prompt. (default: true)
-d, --defaults use default configuration: --template=next --preset=nova (default: false)
-f, --force force overwrite of existing configuration. (default: false)
-c, --cwd <cwd> the working directory. defaults to the current directory.
-n, --name <name> the name for the new project.
-s, --silent mute output. (default: false)
--css-variables use css variables for theming. (default: true)
--no-css-variables do not use css variables for theming.
--monorepo scaffold a monorepo project.
--no-monorepo skip the monorepo prompt.
--rtl enable RTL support.
--no-rtl disable RTL support.
--reinstall re-install existing UI components.
--no-reinstall do not re-install existing UI components.
-h, --help display help for commandThe create command is an alias for init:
npx shadcn@latest createadd
Use the add command to add components and dependencies to your project.
npx shadcn@latest add [component]Options
Usage: shadcn add [options] [components...]
add a component to your project
Arguments:
components name, url or local path to component
Options:
-y, --yes skip confirmation prompt. (default: false)
-o, --overwrite overwrite existing files. (default: false)
-c, --cwd <cwd> the working directory. defaults to the current directory.
-a, --all add all available components (default: false)
-p, --path <path> the path to add the component to.
-s, --silent mute output. (default: false)
--dry-run preview changes without writing files. (default: false)
--diff [path] show diff for a file.
--view [path] show file contents.
-h, --help display help for commandapply
Use the apply command to apply a preset to an existing project.
npx shadcn@latest apply --preset a2r6bwOptions
Usage: shadcn apply [options] [preset]
apply a preset to an existing project
Arguments:
preset the preset to apply
Options:
--preset <preset> preset configuration to apply
-y, --yes skip confirmation prompt. (default: false)
-c, --cwd <cwd> the working directory. defaults to the current directory.
-s, --silent mute output. (default: false)
-h, --help display help for commandview
Use the view command to view items from the registry before installing them.
npx shadcn@latest view [item]You can view multiple items at once:
npx shadcn@latest view button card dialogOr view items from namespaced registries:
npx shadcn@latest view @acme/auth @v0/dashboardOptions
Usage: shadcn view [options] <items...>
view items from the registry
Arguments:
items the item names or URLs to view
Options:
-c, --cwd <cwd> the working directory. defaults to the current directory.
-h, --help display help for commandsearch
Use the search command to search for items from registries.
npx shadcn@latest search [registry]You can search with a query:
npx shadcn@latest search @shadcn -q "button"Or search multiple registries at once:
npx shadcn@latest search @shadcn @v0 @acmeThe list command is an alias for search:
npx shadcn@latest list @acmeOptions
Usage: shadcn search|list [options] <registries...>
search items from registries
Arguments:
registries the registry names or urls to search items from. Names
must be prefixed with @.
Options:
-c, --cwd <cwd> the working directory. defaults to the current directory.
-q, --query <query> query string
-l, --limit <number> maximum number of items to display per registry (default: "100")
-o, --offset <number> number of items to skip (default: "0")
-h, --help display help for commandbuild
Use the build command to generate the registry JSON files.
npx shadcn@latest buildThis command reads the registry.json file and generates the registry JSON files in the public/r directory.
Options
Usage: shadcn build [options] [registry]
build components for a shadcn registry
Arguments:
registry path to registry.json file (default: "./registry.json")
Options:
-o, --output <path> destination directory for json files (default: "./public/r")
-c, --cwd <cwd> the working directory. defaults to the current directory.
-h, --help display help for commandTo customize the output directory, use the --output option.
npx shadcn@latest build --output ./public/registrydocs
Use the docs command to fetch documentation and API references for components.
npx shadcn@latest docs [component]Options
Usage: shadcn docs [options] [component]
fetch documentation and API references for components
Arguments:
component the component to get docs for
Options:
-c, --cwd <cwd> the working directory. defaults to the current directory.
-b, --base <base> the base to use either 'base' or 'radix'. defaults to project base.
--json output as JSON. (default: false)
-h, --help display help for commandinfo
Use the info command to get information about your project.
npx shadcn@latest infoOptions
Usage: shadcn info [options]
get information about your project
Options:
-c, --cwd <cwd> the working directory. defaults to the current directory.
--json output as JSON. (default: false)
-h, --help display help for commandmigrate
Use the migrate command to run migrations on your project.
npx shadcn@latest migrate [migration]Available Migrations
| Migration | Description |
|---|---|
icons |
Migrate your UI components to a different icon library. |
radix |
Migrate to radix-ui. |
rtl |
Migrate your components to support RTL (right-to-left). |
Options
Usage: shadcn migrate [options] [migration] [path]
run a migration.
Arguments:
migration the migration to run.
path optional path or glob pattern to migrate.
Options:
-c, --cwd <cwd> the working directory. defaults to the current directory.
-l, --list list all migrations. (default: false)
-y, --yes skip confirmation prompt. (default: false)
-h, --help display help for commandmigrate rtl
The rtl migration transforms your components to support RTL (right-to-left) languages.
npx shadcn@latest migrate rtlThis will:
- Update
components.jsonto setrtl: true - Transform physical CSS properties to logical equivalents (e.g.,
ml-4→ms-4,text-left→text-start) - Add
rtl:variants where needed (e.g.,space-x-4→space-x-4 rtl:space-x-reverse)
Migrate specific files
You can migrate specific files or use glob patterns:
# Migrate a specific file
npx shadcn@latest migrate rtl src/components/ui/button.tsx
# Migrate files matching a glob pattern
npx shadcn@latest migrate rtl "src/components/ui/**"If no path is provided, the migration will transform all files in your ui directory (from components.json).
migrate radix
The radix migration updates your imports from individual @radix-ui/react-* packages to the unified radix-ui package.
npx shadcn@latest migrate radixThis will:
- Transform imports from
@radix-ui/react-*toradix-ui - Add the
radix-uipackage to yourpackage.json
Before
import * as DialogPrimitive from "@radix-ui/react-dialog"
import * as SelectPrimitive from "@radix-ui/react-select"After
import { Dialog as DialogPrimitive, Select as SelectPrimitive } from "radix-ui"Migrate specific files
You can migrate specific files or use glob patterns:
# Migrate a specific file.
npx shadcn@latest migrate radix src/components/ui/dialog.tsx
# Migrate files matching a glob pattern.
npx shadcn@latest migrate radix "src/components/ui/**"If no path is provided, the migration will transform all files in your ui directory (from components.json).
Once complete, you can remove any unused @radix-ui/react-* packages from your package.json.
Apps V4 Content Docs (Root) Components Json (`apps/v4/content/docs/(root)/components-json.mdx`)
title: components.json
The components.json file holds configuration for your project.
We use it to understand how your project is set up and how to generate components customized for your project.
You can create a components.json file in your project by running the following command:
npx shadcn@latest initSee the CLI section for more information.
$schema
You can see the JSON Schema for components.json here.
{
"$schema": "https://ui.shadcn.com/schema.json"
}style
The style for your components. This cannot be changed after initialization.
{
"style": "new-york"
}The default style has been deprecated. Use the new-york style instead.
tailwind
Configuration to help the CLI understand how Tailwind CSS is set up in your project.
See the installation section for how to set up Tailwind CSS.
tailwind.config
Path to where your tailwind.config.js file is located. For Tailwind CSS v4, leave this blank.
{
"tailwind": {
"config": "tailwind.config.js" | "tailwind.config.ts"
}
}tailwind.css
Path to the CSS file that imports Tailwind CSS into your project.
{
"tailwind": {
"css": "styles/global.css"
}
}tailwind.baseColor
This is used to generate the default theme tokens for your components. This cannot be changed after initialization.
{
"tailwind": {
"baseColor": "neutral" | "stone" | "zinc" | "mauve" | "olive" | "mist" | "taupe"
}
}tailwind.cssVariables
We use and recommend CSS variables for theming.
Set tailwind.cssVariables to true to generate semantic theme tokens like background, foreground, and primary. Set it to false to generate inline Tailwind color utilities instead.
{
"tailwind": {
"cssVariables": `true` | `false`
}
}For more information, see the theming docs.
This cannot be changed after initialization. To switch between CSS variables and utility classes, you'll have to delete and re-install your components.
tailwind.prefix
The prefix to use for your Tailwind CSS utility classes. Components will be added with this prefix.
{
"tailwind": {
"prefix": "tw-"
}
}rsc
Whether or not to enable support for React Server Components.
The CLI automatically adds a use client directive to client components when set to true.
{
"rsc": `true` | `false`
}tsx
Choose between TypeScript or JavaScript components.
Setting this option to false allows components to be added as JavaScript with the .jsx file extension.
{
"tsx": `true` | `false`
}aliases
The CLI uses these values and the paths config from your tsconfig.json or jsconfig.json file to place generated components in the correct location.
Path aliases have to be set up in your tsconfig.json or jsconfig.json file.
aliases.utils
Import alias for your utility functions.
{
"aliases": {
"utils": "@/lib/utils"
}
}aliases.components
Import alias for your components.
{
"aliases": {
"components": "@/components"
}
}aliases.ui
Import alias for ui components.
The CLI will use the aliases.ui value to determine where to place your ui components. Use this config if you want to customize the installation directory for your ui components.
{
"aliases": {
"ui": "@/app/ui"
}
}aliases.lib
Import alias for lib functions such as format-date or generate-id.
{
"aliases": {
"lib": "@/lib"
}
}aliases.hooks
Import alias for hooks such as use-media-query or use-toast.
{
"aliases": {
"hooks": "@/hooks"
}
}registries
Configure multiple resource registries for your project. This allows you to install components, libraries, utilities, and other resources from various sources including private registries.
See the Namespaced Registries documentation for detailed information.
Basic Configuration
Configure registries with URL templates:
{
"registries": {
"@v0": "https://v0.dev/chat/b/{name}",
"@acme": "https://registry.acme.com/{name}.json",
"@internal": "https://internal.company.com/{name}.json"
}
}The {name} placeholder is replaced with the resource name when installing.
Advanced Configuration with Authentication
For private registries that require authentication:
{
"registries": {
"@private": {
"url": "https://api.company.com/registry/{name}.json",
"headers": {
"Authorization": "Bearer ${REGISTRY_TOKEN}",
"X-API-Key": "${API_KEY}"
},
"params": {
"version": "latest"
}
}
}
}Environment variables in the format ${VAR_NAME} are automatically expanded from your environment.
Using Namespaced Registries
Once configured, install resources using the namespace syntax:
# Install from a configured registry
npx shadcn@latest add @v0/dashboard
# Install from private registry
npx shadcn@latest add @private/button
# Install multiple resources
npx shadcn@latest add @acme/header @internal/auth-utilsExample: Multiple Registry Setup
{
"registries": {
"@shadcn": "https://ui.shadcn.com/r/{name}.json",
"@company-ui": {
"url": "https://registry.company.com/ui/{name}.json",
"headers": {
"Authorization": "Bearer ${COMPANY_TOKEN}"
}
},
"@team": {
"url": "https://team.company.com/{name}.json",
"params": {
"team": "frontend",
"version": "${REGISTRY_VERSION}"
}
}
}
}This configuration allows you to:
- Install public components from shadcn/ui
- Access private company UI components with authentication
- Use team-specific resources with versioning
For more information about authentication, see the Authentication documentation.
Apps V4 Content Docs (Root) Directory (`apps/v4/content/docs/(root)/directory.mdx`)
title: Registry Directory
These registries are built into the CLI with no additional configuration required. To add a component, run: npx shadcn add @<registry>/<component>.
Don't see a registry? Learn how to add it here.
Documentation
You can use the shadcn CLI to run your own code registry. Running your own registry allows you to distribute your custom components, hooks, pages, config, rules and other files to any project.
Set up and build your own registry<LinkedCard
href="/docs/registry/authentication"
className="items-start text-sm md:p-6"
Authentication
Secure your registry with authenticationConfigure registries with namespacesLearn how to add a registry to the directoryRegistry item examples and configurationsSchema specification for registry.jsonApps V4 Content Docs (Root) Figma (`apps/v4/content/docs/(root)/figma.mdx`)
title: Figma
Free
- Obra shadcn/ui by Obra Studio - Carefully crafted shadcn/ui kit, MIT licensed, maintained by team of designers, with free design to code plugin
- shadcn/ui components by Sitsiilia Bergmann - A well-structured component library aligned with the shadcn component system, regularly maintained.
- shadcn/ui design system by Pietro Schirano - A design companion for shadcn/ui. Each component was painstakingly crafted to perfectly match the code implementation.
Paid
- shadcn/ui kit by Matt Wierzbicki - A premium, always up-to-date UI kit for Figma - shadcn/ui compatible and optimized for smooth design-to-dev handoff.
- shadcncraft Design System - Production-ready shadcn/ui kit with Pro React blocks and 1:1 Figma alignment. Design and ship faster with tweakcn theming, AI-assisted workflows, and Figma to React export, built for real product UIs.
- shadcn/studio UI Kit - Accelerate design & development with a shadcn/ui compatible Figma kit with updated components, 550+ blocks, 10+ templates, 20+ themes, and an AI tool that converts designs into shadcn/ui code.
- Shadcnblocks.com - A Premium Shadcn Figma UI Kit with components, 500+ pro blocks, shadcn theme variables, light/dark mode and Figma MCP ready.
Apps V4 Content Docs (Root) Javascript (`apps/v4/content/docs/(root)/javascript.mdx`)
title: JavaScript
This project and the components are written in TypeScript. We recommend using TypeScript for your project as well.
However we provide a JavaScript version of the components as well. The JavaScript version is available via the cli.
To opt-out of TypeScript, you can use the tsx flag in your components.json file.
{
"style": "new-york",
"rsc": false,
"tsx": false,
"tailwind": {
"config": "",
"css": "src/app/globals.css",
"baseColor": "zinc",
"cssVariables": true
},
"iconLibrary": "lucide",
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
}
}To configure import aliases, you can use the following jsconfig.json:
{
"compilerOptions": {
"paths": {
"@/*": ["./*"]
}
}
}Apps V4 Content Docs (Root) Legacy (`apps/v4/content/docs/(root)/legacy.mdx`)
title: Legacy Docs
You're looking at the docs for shadcn/ui + Tailwind v4. If you're looking for the docs for shadcn/ui + Tailwind v3, you can find them here.
View the legacy docsApps V4 Content Docs (Root) Mcp (`apps/v4/content/docs/(root)/mcp.mdx`)
title: MCP Server
The shadcn MCP Server allows AI assistants to interact with items from registries. You can browse available components, search for specific ones, and install them directly into your project using natural language.
For example, you can ask an AI assistant to "Build a landing page using components from the acme registry" or "Find me a login form from the shadcn registry".
Registries are configured in your project's components.json file.
{
"registries": {
"@acme": "https://acme.com/r/{name}.json"
}
}Quick Start
Select your MCP client and follow the instructions to configure the shadcn MCP server. If you'd like to do it manually, see the Configuration section.
**Restart Claude Code** and try the following prompts:
- Show me all available components in the shadcn registry
- Add the button, dialog and card components to my project
- Create a contact form using components from the shadcn registry
**Note:** You can use `/mcp` command in Claude Code to debug the MCP server.Open **Cursor Settings** and **Enable the MCP server** for shadcn. Then try the following prompts:
- Show me all available components in the shadcn registry
- Add the button, dialog and card components to my project
- Create a contact form using components from the shadcn registryOpen `.vscode/mcp.json` and click **Start** next to the shadcn server. Then try the following prompts with GitHub Copilot:
- Show me all available components in the shadcn registry
- Add the button, dialog and card components to my project
- Create a contact form using components from the shadcn registry**Run the following command** in your project:
```bash
npx shadcn@latest mcp init --client codex
```
**Then, add the following configuration** to `~/.codex/config.toml`:
```toml
[mcp_servers.shadcn]
command = "npx"
args = ["shadcn@latest", "mcp"]
```
**Restart Codex** and try the following prompts:
- Show me all available components in the shadcn registry
- Add the button, dialog and card components to my project
- Create a contact form using components from the shadcn registry**Restart OpenCode** and try the following prompts:
- Show me all available components in the shadcn registry
- Add the button, dialog and card components to my project
- Create a contact form using components from the shadcn registryWhat is MCP?
Model Context Protocol (MCP) is an open protocol that enables AI assistants to securely connect to external data sources and tools. With the shadcn MCP server, your AI assistant gains direct access to:
- Browse Components - List all available components, blocks, and templates from any configured registry
- Search Across Registries - Find specific components by name or functionality across multiple sources
- Install with Natural Language - Add components using simple conversational prompts like "add a login form"
- Support for Multiple Registries - Access public registries, private company libraries, and third-party sources
How It Works
The MCP server acts as a bridge between your AI assistant, component registries and the shadcn CLI.
- Registry Connection - MCP connects to configured registries (shadcn/ui, private registries, third-party sources)
- Natural Language - You describe what you need in plain English
- AI Processing - The assistant translates your request into registry commands
- Component Delivery - Resources are fetched and installed in your project
Supported Registries
The shadcn MCP server works out of the box with any shadcn-compatible registry.
- shadcn/ui Registry - The default registry with all shadcn/ui components
- Third-Party Registries - Any registry following the shadcn registry specification
- Private Registries - Your company's internal component libraries
- Namespaced Registries - Multiple registries configured with
@namespacesyntax
Configuration
You can use any MCP client to interact with the shadcn MCP server. Here are the instructions for the most popular ones.
Claude Code
To use the shadcn MCP server with Claude Code, add the following configuration to your project's .mcp.json file:
{
"mcpServers": {
"shadcn": {
"command": "npx",
"args": ["shadcn@latest", "mcp"]
}
}
}After adding the configuration, restart Claude Code and run /mcp to see the shadcn MCP server in the list. If you see Connected, you're good to go.
See the Claude Code MCP documentation for more details.
Cursor
To configure MCP in Cursor, add the shadcn server to your project's .cursor/mcp.json configuration file:
{
"mcpServers": {
"shadcn": {
"command": "npx",
"args": ["shadcn@latest", "mcp"]
}
}
}After adding the configuration, enable the shadcn MCP server in Cursor Settings.
Once enabled, you should see a green dot next to the shadcn server in the MCP server list and a list of available tools.
See the Cursor MCP documentation for more details.
VS Code
To configure MCP in VS Code with GitHub Copilot, add the shadcn server to your project's .vscode/mcp.json configuration file:
{
"servers": {
"shadcn": {
"command": "npx",
"args": ["shadcn@latest", "mcp"]
}
}
}After adding the configuration, open .vscode/mcp.json and click Start next to the shadcn server.
See the VS Code MCP documentation for more details.
Codex
To configure MCP in Codex, add the shadcn server to ~/.codex/config.toml:
[mcp_servers.shadcn]
command = "npx"
args = ["shadcn@latest", "mcp"]After adding the configuration, restart Codex to load the MCP server.
Configuring Registries
The MCP server supports multiple registries through your project's components.json configuration. This allows you to access components from various sources including private registries and third-party providers.
Configure additional registries in your components.json:
{
"registries": {
"@acme": "https://registry.acme.com/{name}.json",
"@internal": {
"url": "https://internal.company.com/{name}.json",
"headers": {
"Authorization": "Bearer ${REGISTRY_TOKEN}"
}
}
}
}Authentication
For private registries requiring authentication, set environment variables in your .env.local:
REGISTRY_TOKEN=your_token_here
API_KEY=your_api_key_hereFor more details on registry authentication, see the Authentication documentation.
Example Prompts
Once the MCP server is configured, you can use natural language to interact with registries. Try one of the following prompts:
Browse & Search
- Show me all available components in the shadcn registry
- Find me a login form from the shadcn registry
Install Items
- Add the button component to my project
- Create a login form using shadcn components
- Install the Cursor rules from the acme registry
Work with Namespaces
- Show me components from acme registry
- Install @internal/auth-form
- Build me a landing page using hero, features and testimonials sections from the acme registry
Troubleshooting
MCP Not Responding
If the MCP server isn't responding to prompts:
- Check Configuration - Verify the MCP server is properly configured and enabled in your MCP client
- Restart MCP Client - Restart your MCP client after configuration changes
- Verify Installation - Ensure
shadcnis installed in your project - Check Network - Confirm you can access the configured registries
Registry Access Issues
If components aren't loading from registries:
- Check components.json - Verify registry URLs are correct
- Test Authentication - Ensure environment variables are set for private registries
- Verify Registry - Confirm the registry is online and accessible
- Check Namespace - Ensure namespace syntax is correct (
@namespace/component)
Installation Failures
If components fail to install:
- Check Project Setup - Ensure you have a valid
components.jsonfile - Verify Paths - Confirm the target directories exist
- Check Permissions - Ensure write permissions for component directories
- Review Dependencies - Check that required dependencies are installed
No Tools or Prompts
If you see the No tools or prompts message, try the following:
- Clear the npx cache - Run
npx clear-npx-cache - Re-enable the MCP server - Try to re-enable the MCP server in your MCP client
- Check Logs - In Cursor, you can see the logs under View -> Output and select
MCP: project-*in the dropdown.
Learn More
- Registry Documentation - Complete guide to shadcn registries
- Namespaces - Configure multiple registry sources
- Authentication - Secure your private registries
- MCP Specification - Learn about Model Context Protocol
Apps V4 Content Docs (Root) Meta.Json (`apps/v4/content/docs/(root)/meta.json`)
{
"title": "Get Started",
"pages": [
"index",
"Installation",
"components-json",
"theming",
"Dark Mode",
"RTL",
"CLI",
"monorepo",
"skills",
"v0",
"javascript",
"blocks",
"figma",
"Changelog",
"llms.txt",
"legacy",
"!new"
]
}
Apps V4 Content Docs (Root) Monorepo (`apps/v4/content/docs/(root)/monorepo.mdx`)
title: Monorepo
Until now, using shadcn/ui in a monorepo was a bit of a pain. You could add
components using the CLI, but you had to manage where the components
were installed and manually fix import paths.
With the new monorepo support in the CLI, we've made it a lot easier to use
shadcn/ui in a monorepo.
The CLI now understands the monorepo structure and will install the components,
dependencies and registry dependencies to the correct paths and handle imports
for you.
Getting started
Create a new monorepo project
To create a new monorepo project, run the init command with the --monorepo flag.
npx shadcn@latest init --monorepoThen select the template you want to use.
? Select a template ›
❯ Next.js
Vite
TanStack Start
React Router
AstroThis will create a new monorepo project with two workspaces: web and ui,
and Turborepo as the build system.
Everything is set up for you, so you can start adding components to your project.
Add components to your project
To add components to your project, run the add command in the path of your app.
cd apps/webnpx shadcn@latest add [COMPONENT]The CLI will figure out what type of component you are adding and install the
correct files to the correct path.
For example, if you run npx shadcn@latest add button, the CLI will install the button component under packages/ui and update the import path for components in apps/web.
If you run npx shadcn@latest add login-01, the CLI will install the button, label, input and card components under packages/ui and the login-form component under apps/web/components.
Importing components
You can import components from the @workspace/ui package as follows:
import { Button } from "@workspace/ui/components/button"You can also import hooks and utilities from the @workspace/ui package.
import { useTheme } from "@workspace/ui/hooks/use-theme"
import { cn } from "@workspace/ui/lib/utils"File Structure
When you create a new monorepo project, the CLI will create the following file structure:
apps
└── web # Your app goes here.
├── app
│ └── page.tsx
├── components
│ └── login-form.tsx
├── components.json
└── package.json
packages
└── ui # Your components and dependencies are installed here.
├── src
│ ├── components
│ │ └── button.tsx
│ ├── hooks
│ ├── lib
│ │ └── utils.ts
│ └── styles
│ └── globals.css
├── components.json
└── package.json
package.json
turbo.jsonRequirements
Every workspace must have a
components.jsonfile. Apackage.jsonfile tells npm how to install the dependencies. Acomponents.jsonfile tells the CLI how and where to install components.The
components.jsonfile must properly define aliases for the workspace. This tells the CLI how to import components, hooks, utilities, etc.
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "radix-nova",
"rsc": true,
"tsx": true,
"tailwind": {
"config": "",
"css": "../../packages/ui/src/styles/globals.css",
"baseColor": "neutral",
"cssVariables": true
},
"iconLibrary": "lucide",
"aliases": {
"components": "@/components",
"hooks": "@/hooks",
"lib": "@/lib",
"utils": "@workspace/ui/lib/utils",
"ui": "@workspace/ui/components"
}
}{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "radix-nova",
"rsc": true,
"tsx": true,
"tailwind": {
"config": "",
"css": "src/styles/globals.css",
"baseColor": "neutral",
"cssVariables": true
},
"iconLibrary": "lucide",
"aliases": {
"components": "@workspace/ui/components",
"utils": "@workspace/ui/lib/utils",
"hooks": "@workspace/ui/hooks",
"lib": "@workspace/ui/lib",
"ui": "@workspace/ui/components"
}
}Ensure you have the same
style,iconLibraryandbaseColorin bothcomponents.jsonfiles.For Tailwind CSS v4, leave the
tailwindconfig empty in thecomponents.jsonfile.
By following these requirements, the CLI will be able to install ui components, blocks, libs and hooks to the correct paths and handle imports for you.
Apps V4 Content Docs (Root) New (`apps/v4/content/docs/(root)/new.mdx`)
title: Your project is ready!
Here are a few things you can do to get started building with shadcn/ui.
Add Components
Use the CLI to add components to your project.
npx shadcn@latest add buttonThen import and use it in your code.
import { Button } from "@/components/ui/button"
export default function Home() {
return <Button>Click me</Button>
}Unlike traditional component libraries, shadcn/ui adds the component source code directly to your project under components/ui/. You own the code and can customize it however you want.
You can add multiple components at once or add all available components.
npx shadcn@latest add button card input labelnpx shadcn@latest add --allBrowse all components on the Components page.
Customize Your Theme
You can edit your theme directly in your CSS file. Learn more about Theming and how to use CSS variables or utility classes.
If you want to try a new preset, you can create a custom theme visually on ui.shadcn.com and apply it to your project using a preset code.
npx shadcn@latest init --preset [CODE]Add a block
You can add a block to your project using the CLI.
npx shadcn@latest add login-03This will add the login-03 block to your project. Import and use it in your code.
import { Login03 } from "@/components/login-03"
export default function Home() {
return <Login03 />
}Install from Registries
shadcn/ui has a growing ecosystem of community registries. You can install components from any registry URL using the CLI.
npx shadcn@latest add @[registry]/[name]Browse the Registry Directory for a list of available registries.
Use AI to Build
shadcn/ui is designed to work with AI. Your AI assistant can read the component source code in your project, understand the APIs, and compose them together to build pages and features.
Here are some example prompts to try:
- "Create a signup page with a form for entering name, email and password."
- "Create a settings page with a form for updating profile information."
- "Build a dashboard with a header, stats cards, and a data table."
Install the shadcn Skills
Install the shadcn skill in your AI assistant. This will give your AI assistant access to the full component registry, documentation, and search.
npx skills add shadcn/uiLearn more about skills.
Connect the MCP Server
The shadcn MCP server gives your AI assistant access to the full component registry, documentation, and search. Connect it in your editor for the best experience.
npx shadcn@latest mcp initLearn more on the MCP Server page.
Apps V4 Content Docs (Root) React 19 (`apps/v4/content/docs/(root)/react-19.mdx`)
title: Next.js 15 + React 19
TL;DR
If you're using npm, you can install shadcn/ui dependencies with a flag. The shadcn CLI will prompt you to select a flag when you run it. No flags required for pnpm, bun, or yarn.
See Upgrade Status for the status of React 19 support for each package.
What's happening?
React 19 is now rc and is tested and supported in the latest Next.js 15 release.
To support React 19, package maintainers will need to test and update their packages to include React 19 as a peer dependency. This is already in progress.
"peerDependencies": {
- "react": "^16.8 || ^17.0 || ^18.0",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0",
- "react-dom": "^16.8 || ^17.0 || ^18.0"
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0"
},In the meantime, if you are installing a package that does not list React 19 as a peer dependency, you will see an error message like this:
npm error code ERESOLVE
npm error ERESOLVE unable to resolve dependency tree
npm error
npm error While resolving: [email protected]
npm error Found: [email protected]
npm error node_modules/react
npm error react@"19.0.0-rc-69d4b800-20241021" from the root projectHow to fix this
Solution 1: `--force` or `--legacy-peer-deps`
You can force install a package with the --force or the --legacy-peer-deps flag.
npm i <package> --force
npm i <package> --legacy-peer-depsThis will install the package and ignore the peer dependency warnings.
- `--force`: Ignores and overrides any dependency conflicts, forcing the
installation of packages.
- `--legacy-peer-deps`: Skips strict peer dependency checks, allowing
installation of packages with unmet peer dependencies to avoid errors.
</AccordionContent>Solution 2: Use React 18
You can downgrade react and react-dom to version 18, which is compatible with the package you are installing and upgrade when the dependency is updated.
npm i react@18 react-dom@18Whichever solution you choose, make sure you test your app thoroughly to ensure
there are no regressions.
Using shadcn/ui on Next.js 15
Using pnpm, bun, or yarn
Follow the instructions in the installation guide to install shadcn/ui. No flags are needed.
Using npm
When you run npx shadcn@latest init -d, you will be prompted to select an option to resolve the peer dependency issues.
It looks like you are using React 19.
Some packages may fail to install due to peer dependency issues (see https://ui.shadcn.com/react-19).
? How would you like to proceed? › - Use arrow-keys. Return to submit.
❯ Use --force
Use --legacy-peer-depsYou can then run the command with the flag you choose.
Adding components
The process for adding components is the same as above. Select a flag to resolve the peer dependency issues.
Remember to always test your app after installing new dependencies.
Upgrade Status
To make it easy for you to track the progress of the upgrade, here is a table with the React 19 support status for the shadcn/ui dependencies.
- ✅ - Works with React 19 using npm, pnpm, and bun.
- 🚧 - Works with React 19 using pnpm and bun. Requires flag for npm. PR is in progress.
| Package | Status | Note |
|---|---|---|
| radix-ui | ✅ | |
| lucide-react | ✅ | |
| class-variance-authority | ✅ | Does not list React 19 as a peer dependency. |
| tailwindcss-animate | ✅ | Does not list React 19 as a peer dependency. |
| embla-carousel-react | ✅ | |
| recharts | ✅ | See note below |
| react-hook-form | ✅ | |
| react-resizable-panels | ✅ | |
| sonner | ✅ | |
| react-day-picker | ✅ | Works with flag for npm. Work to upgrade to v9 in progress. |
| input-otp | ✅ | |
| vaul | ✅ | |
| @radix-ui/react-icons | ✅ | See PR #194 |
| cmdk | ✅ |
If you have any questions, please open an issue on GitHub.
Recharts
To use recharts with React 19, you will need to override the react-is dependency.
package.json
"overrides": {
"react-is": "^19.0.0-rc-69d4b800-20241021"
}Note: the react-is version needs to match the version of React 19 you are using. The above is an example.
npm install --legacy-peer-deps
Apps V4 Content Docs (Root) Skills (`apps/v4/content/docs/(root)/skills.mdx`)
title: Skills
Skills give AI assistants like Claude Code project-aware context about shadcn/ui. When installed, your AI assistant knows how to find, install, compose, and customize components using the correct APIs and patterns for your project.
For example, you can ask your AI assistant to:
- "Add a login form with email and password fields."
- "Create a settings page with a form for updating profile information."
- "Build a dashboard with a sidebar, stats cards, and a data table."
- "Switch to --preset [CODE]"
- "Can you add a hero from @tailark?"
The skill reads your project's components.json and provides the assistant with your framework, aliases, installed components, icon library, and base library so it can generate correct code on the first try.
Install
npx skills add shadcn/uiThis installs the shadcn skill into your project. Once installed, your AI assistant automatically loads it when working with shadcn/ui components.
Learn more about skills at skills.sh.
What's Included
The skill provides your AI assistant with the following knowledge:
Project Context
On every interaction, the skill runs shadcn info --json to get your project's configuration: framework, Tailwind version, aliases, base library (radix or base), icon library, installed components, and resolved file paths.
CLI Commands
Full reference for all CLI commands: init, add, search, view, docs, diff, info, and build. Includes flags, dry-run mode, smart merge workflows, presets, and templates.
Theming and Customization
How CSS variables, OKLCH colors, dark mode, custom colors, border radius, and component variants work. Includes guidance for both Tailwind v3 and v4.
Registry Authoring
How to build and publish custom component registries: registry.json format, item types, file objects, dependencies, CSS variables, building, hosting, and user configuration.
MCP Server
Setup and tools for the shadcn MCP server, which lets AI assistants search, browse, and install components from registries.
How It Works
- Project detection — The skill activates when it finds a
components.jsonfile in your project. - Context injection — It runs
shadcn info --jsonto read your project configuration and injects the result into the assistant's context. - Pattern enforcement — The assistant follows shadcn/ui composition rules: using
FieldGroupfor forms,ToggleGroupfor option sets, semantic colors, and correct base-specific APIs. - Component discovery — The assistant uses
shadcn docs,shadcn search, or MCP tools to find components and their documentation before generating code.
Learn More
- CLI — Full CLI command reference
- MCP Server — Connect the MCP server for registry access
- Theming — CSS variables and customization
- Registry — Building and publishing custom registries
- skills.sh — Learn more about AI skills
Apps V4 Content Docs (Root) Tailwind V4 (`apps/v4/content/docs/(root)/tailwind-v4.mdx`)
title: Tailwind v4
It’s here! Tailwind v4 and React 19. Ready for you to try out. You can start using it today.
What's New
- The CLI can now initialize projects with Tailwind v4.
- Full support for the new
@themedirective and@theme inlineoption. - All components are updated for Tailwind v4 and React 19.
- We’ve removed the forwardRefs and adjusted the types.
- Every primitive now has a
data-slotattribute for styling. - We've fixed and cleaned up the style of the components.
- We're deprecating the
toastcomponent in favor ofsonner. - Buttons now use the default cursor.
- We're deprecating the
defaultstyle. New projects will usenew-york. - HSL colors are now converted to OKLCH.
Note: this is non-breaking. Your existing apps with Tailwind v3 and React 18 will still work. When you add new components, they'll still be in v3 and React 18 until you upgrade. Only new projects start with Tailwind v4 and React 19.
Try It Out
You can start using Tailwind v4 + React 19 today. See the framework specific guides below for how to get started.
Upgrade Your Project
One of the major advantages of using shadcn/ui is that the code you end up with is exactly what you'd write yourself. There are no hidden abstractions.
This means when a dependency has a new release, you can just follow the official upgrade paths.
Here's how to upgrade your existing projects (full docs are on the way):
1. Follow the Tailwind v4 Upgrade Guide
- Upgrade to Tailwind v4 by following the official upgrade guide: https://tailwindcss.com/docs/upgrade-guide
- Use the
@tailwindcss/upgrade@nextcodemod to remove deprecated utility classes and update tailwind config.
2. Update your CSS variables
The codemod will migrate your CSS variables as references under the @theme directive.
@layer base {
:root {
--background: 0 0% 100%;
--foreground: 0 0% 3.9%;
}
}
@theme {
--color-background: hsl(var(--background));
--color-foreground: hsl(var(--foreground));
}This works. But to make it easier to work with colors and other variables, we'll need to move the hsl wrappers and use @theme inline.
Here's how you do it:
- Move
:rootand.darkout of the@layerbase. - Wrap the color values in
hsl() - Add the
inlineoption to@themei.e@theme inline - Remove the
hsl()wrappers from@theme
:root {
--background: hsl(0 0% 100%); // <-- Wrap in hsl
--foreground: hsl(0 0% 3.9%);
}
.dark {
--background: hsl(0 0% 3.9%); // <-- Wrap in hsl
--foreground: hsl(0 0% 98%);
}
@theme inline {
--color-background: var(--background); // <-- Remove hsl
--color-foreground: var(--foreground);
}This change makes it much simpler to access your theme variables in both utility classes and outside of CSS, e.g. using color values in JavaScript.
3. Update colors for charts
Now that the theme colors come with hsl(), you can remove the wrapper in your chartConfig:
const chartConfig = {
desktop: {
label: "Desktop",
- color: "hsl(var(--chart-1))",
+ color: "var(--chart-1)",
},
mobile: {
label: "Mobile",
- color: "hsl(var(--chart-2))",
+ color: "var(--chart-2)",
},
} satisfies ChartConfig4. Use new `size-*` utility
The new size-* utility (added in Tailwind v3.4), is now fully supported by tailwind-merge. You can replace w-* h-* with the new size-* utility:
- w-4 h-4
+ size-45. Update your dependencies
pnpm up "@radix-ui/*" cmdk lucide-react recharts tailwind-merge clsx --latest6. Remove forwardRef
You can use the remove-forward-ref codemod to migrate your forwardRef to props or manually update the primitives.
For the codemod, see https://github.com/reactjs/react-codemod#remove-forward-ref.
If you want to do it manually, here's how to do it step by step:
- Replace
React.forwardRef<...>withReact.ComponentProps<...> - Remove
ref={ref}from the component. - Add a
data-slotattribute. This will come in handy for styling with Tailwind. - You can optionally convert to a named function and remove the
displayName.
Before
const AccordionItem = React.forwardRef<
React.ElementRef<typeof AccordionPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Item>
>(({ className, ...props }, ref) => (
<AccordionPrimitive.Item
ref={ref}
className={cn("border-b last:border-b-0", className)}
{...props}
/>
))
AccordionItem.displayName = "AccordionItem"After
function AccordionItem({
className,
...props
}: React.ComponentProps<typeof AccordionPrimitive.Item>) {
return (
<AccordionPrimitive.Item
data-slot="accordion-item"
className={cn("border-b last:border-b-0", className)}
{...props}
/>
)
}Changelog
March 19, 2025 - Deprecate `tailwindcss-animate`
We've deprecated tailwindcss-animate in favor of tw-animate-css.
New projects will have tw-animate-css installed by default.
For existing projects, follow the steps below to migrate.
- Remove
tailwindcss-animatefrom your dependencies. - Remove the
@plugin 'tailwindcss-animate'from your globals.css file. - Install
tw-animate-cssas a dev dependency. - Add the
@import "tw-animate-css"to your globals.css file.
- @plugin 'tailwindcss-animate';
+ @import "tw-animate-css";March 12, 2025 - New Dark Mode Colors
We've revisited the dark mode colors and updated them to be more accessible.
If you're running an existing Tailwind v4 project (not an upgraded one[^1]), you can update your components to use the new dark mode colors by re-adding your components using the CLI[^2].
The CLI will overwrite your existing components. We recommend committing any changes you've made to your components before running the CLI.
git add .
git commit -m "..."npx shadcn@latest add --all --overwriteUpdate the dark mode colors in your globals.css file to new OKLCH colors. See the Base Colors reference for a list of colors.
Review and re-apply any changes you made to your components.
[^1]: Upgraded projects are not affected by this change. You can continue using the old dark mode colors.
[^2]: Updating your components will overwrite your existing components.
Apps V4 Content Docs (Root) Theming (`apps/v4/content/docs/(root)/theming.mdx`)
title: Theming
Want to build your theme visually? Use shadcn/create to preview colors, radius, fonts, and icons, then generate a preset for your project.
We use and recommend CSS variables for theming.
This gives you semantic theme tokens like background, foreground, and primary that components use by default. Override those tokens in your CSS to change the look of your app without rewriting component classes.
<div className="bg-background text-foreground" />To use CSS variables for theming, set tailwind.cssVariables to true in your components.json file. This is the default.
{
"style": "base-nova",
"rsc": true,
"tailwind": {
"config": "",
"css": "app/globals.css",
"baseColor": "neutral",
"cssVariables": true
}
}Tailwind maps these tokens into utilities like bg-background, text-foreground, border-border, and ring-ring.
Dark mode works by overriding the same tokens inside a .dark selector. See the dark mode docs for adding a theme provider and toggling the .dark class.
Token Convention
We use semantic background and foreground pairs. The base token controls the surface color and the -foreground token controls the text and icon color that sits on that surface.
The background suffix is omitted for the surface token. For example, primary pairs with primary-foreground.
Given the following CSS variables:
--primary: oklch(0.205 0 0);
--primary-foreground: oklch(0.985 0 0);The background color of the following component will be var(--primary) and the foreground color will be var(--primary-foreground).
<div className="bg-primary text-primary-foreground">Hello</div>Theme Tokens
These tokens live in your CSS file under :root and .dark.
| Token | What it controls | Used by |
|---|---|---|
background / foreground |
The default app background and text color. | The page shell, page sections, and default text. |
card / card-foreground |
Elevated surfaces and the content inside them. | Card, dashboard panels, settings panels. |
popover / popover-foreground |
Floating surfaces and the content inside them. | Popover, DropdownMenu, ContextMenu, and other overlays. |
primary / primary-foreground |
High-emphasis actions and brand surfaces. | Default Button, selected states, badges, and active accents. |
secondary / secondary-foreground |
Lower-emphasis filled actions and supporting surfaces. | Secondary buttons, secondary badges, and supporting UI. |
muted / muted-foreground |
Subtle surfaces and lower-emphasis content. | Descriptions, placeholders, empty states, helper text, and subdued surfaces. |
accent / accent-foreground |
Interactive hover, focus, and active surfaces. | Ghost buttons, menu highlight states, hovered rows, and selected items. |
destructive |
Destructive actions and error emphasis. | Destructive buttons, invalid states, and destructive menu items. |
border |
Default borders and separators. | Cards, menus, tables, separators, and layout dividers. |
input |
Form control borders and input surface treatment. | Input, Textarea, Select, and outline-style controls. |
ring |
Focus rings and outlines. | Buttons, inputs, checkboxes, menus, and other focusable controls. |
chart-1 ... chart-5 |
The default chart palette. | Charts and chart-driven dashboard blocks. |
sidebar / sidebar-foreground |
The base sidebar surface and default sidebar text. | The Sidebar container and its default content. |
sidebar-primary / sidebar-primary-foreground |
High-emphasis actions inside the sidebar. | Active items, icon tiles, badges, and sidebar CTAs. |
sidebar-accent / sidebar-accent-foreground |
Hover and selected states inside the sidebar. | Sidebar menu hover states, open items, and interactive rows. |
sidebar-border |
Sidebar-specific borders and separators. | Sidebar headers, groups, and internal dividers. |
sidebar-ring |
Sidebar-specific focus rings. | Focused controls inside the sidebar. |
radius |
The base corner radius scale. | Cards, inputs, buttons, popovers, and the derived radius-* tokens. |
The chart tokens are covered in more detail in the Chart theming docs.
Radius Scale
--radius is the base radius token for your theme.
We derive a small radius scale from it so components can use consistent corner sizes while still sharing a single source of truth.
@theme inline {
--radius-sm: calc(var(--radius) * 0.6);
--radius-md: calc(var(--radius) * 0.8);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) * 1.4);
--radius-2xl: calc(var(--radius) * 1.8);
--radius-3xl: calc(var(--radius) * 2.2);
--radius-4xl: calc(var(--radius) * 2.6);
}This means:
radius-lgis the base value.- Smaller radii scale down from
--radius. - Larger radii scale up from
--radius. - Changing
--radiusupdates the entire radius scale.
Adding New Tokens
To add a new token, define it under :root and .dark, then expose it to Tailwind with @theme inline.
:root {
--warning: oklch(0.84 0.16 84);
--warning-foreground: oklch(0.28 0.07 46);
}
.dark {
--warning: oklch(0.41 0.11 46);
--warning-foreground: oklch(0.99 0.02 95);
}
@theme inline {
--color-warning: var(--warning);
--color-warning-foreground: var(--warning-foreground);
}You can now use bg-warning and text-warning-foreground in your components.
<div className="bg-warning text-warning-foreground" />Base Colors
tailwind.baseColor controls the default token values generated for your project when you run init or use a preset.
The available base colors are: Neutral, Stone, Zinc, Mauve, Olive, Mist, and Taupe.
Default Theme CSS
The following is the full default neutral theme scaffold. Copy it into your global CSS file and adjust the tokens as needed.
/* Detailed source-code truncated for AI context efficiency. */Without CSS Variables
If you do not want to use CSS variables, the CLI can generate components with inline Tailwind color utilities instead.
npx shadcn@latest init --no-css-variablesThis sets tailwind.cssVariables to false in your components.json file.
<div className="bg-zinc-950 text-zinc-50 dark:bg-white dark:text-zinc-950" />This is an installation-time choice. To switch an existing project, delete and re-install your components.
Apps V4 Content Docs (Root) V0 (`apps/v4/content/docs/(root)/v0.mdx`)
title: Open in v0
Every component on ui.shadcn.com is editable on v0 by Vercel. This allows you to easily customize the components in natural language and paste into your app.
Open in v0
To use v0, sign-up for a free Vercel account here. In addition to v0, this gives you free access to Vercel's frontend cloud platform by the creators of Next.js, where you can deploy and host your project for free.
Learn more about getting started with Vercel here.
Learn more about getting started with v0 here.
Apps V4 Content Docs Changelog 2023 06 New Cli (`apps/v4/content/docs/changelog/2023-06-new-cli.mdx`)
title: June 2023 - New CLI, Styles and more date: 2023-06-22
I have a lot of updates to share with you today:
- New CLI - Rewrote the CLI from scratch. You can now add components, dependencies and configure import paths.
- Theming - Choose between using CSS variables or Tailwind CSS utility classes for theming.
- Base color - Configure the base color for your project. This will be used to generate the default color palette for your components.
- React Server Components - Opt out of using React Server Components. The CLI will automatically append or remove the
use clientdirective. - Styles - Introducing a new concept called Style. A style comes with its own set of components, animations, icons and more.
- Exit animations - Added exit animations to all components.
- Other updates - New
iconbutton size, updatedsheetcomponent and more. - Updating your project - How to update your project to get the latest changes.
New CLI
I've been working on a new CLI for the past few weeks. It's a complete rewrite. It comes with a lot of new features and improvements.
`init`
npx shadcn@latest initWhen you run the init command, you will be asked a few questions to configure components.json:
Which style would you like to use? › Default
Which color would you like to use as base color? › Slate
Where is your global CSS file? › › app/globals.css
Do you want to use CSS variables for colors? › no / yes
Where is your tailwind.config.js located? › tailwind.config.js
Configure the import alias for components: › @/components
Configure the import alias for utils: › @/lib/utils
Are you using React Server Components? › no / yesThis file contains all the information about your components: where to install them, the import paths, how they are styled...etc.
You can use this file to change the import path of a component, set a baseColor or change the styling method.
{
"style": "default",
"tailwind": {
"config": "tailwind.config.ts",
"css": "src/app/globals.css",
"baseColor": "zinc",
"cssVariables": true
},
"rsc": false,
"aliases": {
"utils": "~/lib/utils",
"components": "~/components"
}
}This means you can now use the CLI with any directory structure including src and app directories.
`add`
npx shadcn@latest addThe add command is now much more capable. You can now add UI components but also import more complex components (coming soon).
The CLI will automatically resolve all components and dependencies, format them based on your custom config and add them to your project.
`diff` (experimental)
npx shadcn diffWe're also introducing a new diff command to help you keep track of upstream updates.
You can use this command to see what has changed in the upstream repository and update your project accordingly.
Run the diff command to get a list of components that have updates available:
npx shadcn diffThe following components have updates available:
- button
- /path/to/my-app/components/ui/button.tsx
- toast
- /path/to/my-app/components/ui/use-toast.ts
- /path/to/my-app/components/ui/toaster.tsxThen run diff [component] to see the changes:
npx shadcn diff alertconst alertVariants = cva(
- "relative w-full rounded-lg border",
+ "relative w-full pl-12 rounded-lg border"
)Theming with CSS Variables or Tailwind Colors
You can choose between using CSS variables or Tailwind CSS utility classes for theming.
When you add new components, the CLI will automatically use the correct theming methods based on your components.json configuration.
Utility classes
<div className="bg-zinc-950 dark:bg-white" />To use utility classes for theming set tailwind.cssVariables to false in your components.json file.
{
"tailwind": {
"config": "tailwind.config.js",
"css": "app/globals.css",
"baseColor": "slate",
"cssVariables": false
}
}CSS Variables
<div className="bg-background text-foreground" />To use CSS variables classes for theming set tailwind.cssVariables to true in your components.json file.
{
"tailwind": {
"config": "tailwind.config.js",
"css": "app/globals.css",
"baseColor": "slate",
"cssVariables": true
}
}Base color
You can now configure the base color for your project. This will be used to generate the default color palette for your components.
{
"tailwind": {
"config": "tailwind.config.js",
"css": "app/globals.css",
"baseColor": "zinc",
"cssVariables": false
}
}Choose between gray, neutral, slate, stone or zinc.
If you have cssVariables set to true, we will set the base colors as CSS variables in your globals.css file. If you have cssVariables set to false, we will inline the Tailwind CSS utility classes in your components.
React Server Components
If you're using a framework that does not support React Server Components, you can now opt out by setting rsc to false. We will automatically append or remove the use client directive when adding components.
{
"rsc": false
}Styles
We are introducing a new concept called Style.
You can think of style as the visual foundation: shapes, icons, animations & typography. A style comes with its own set of components, animations, icons and more.
We are shipping two styles: default and new-york (with more coming soon).
The default style is the one you are used to. It's the one we've been using since the beginning of this project. It uses lucide-react for icons and tailwindcss-animate for animations.
The new-york style is a new style. It ships with smaller buttons, cards with shadows and a new set of icons from Radix Icons.
When you run the init command, you will be asked which style you would like to use. This is saved in your components.json file.
{
"style": "new-york"
}Theming
Start with a style as the base then theme using CSS variables or Tailwind CSS utility classes to completely change the look of your components.
Exit animations
I added exit animations to all components. Click on the combobox below to see the subtle exit animation.
The animations can be customized using utility classes.
Other updates
Button
- Added a new button size
icon:
Sheet
- Renamed
positiontosideto match the other elements.
- Removed the
sizeprops. UseclassName="w-[200px] md:w-[450px]"for responsive sizing.
Updating your project
Since we follow a copy and paste approach, you will need to manually update your project to get the latest changes.
Add `components.json`
Creating a components.json file at the root:
{
"style": "default",
"rsc": true,
"tailwind": {
"config": "tailwind.config.js",
"css": "app/globals.css",
"baseColor": "slate",
"cssVariables": true
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils"
}
}Update the values for tailwind.css and aliases to match your project structure.
Button
Add the icon size to the buttonVariants:
const buttonVariants = cva({
variants: {
size: {
default: "h-10 px-4 py-2",
sm: "h-9 rounded-md px-3",
lg: "h-11 rounded-md px-8",
icon: "h-10 w-10",
},
},
})Sheet
- Replace the content of
sheet.tsxwith the following:
/* Detailed source-code truncated for AI context efficiency. */- Rename
positiontoside
- <Sheet position="right" />
+ <Sheet side="right" />Thank you
I'd like to thank everyone who has been using this project, providing feedback and contributing to it. I really appreciate it. Thank you.
Apps V4 Content Docs Changelog 2023 07 Javascript (`apps/v4/content/docs/changelog/2023-07-javascript.mdx`)
title: July 2023 - JavaScript date: 2023-07-04
This project and the components are written in TypeScript. We recommend using TypeScript for your project as well.
However we provide a JavaScript version of the components, available via the cli.
Would you like to use TypeScript (recommended)? noTo opt-out of TypeScript, you can use the tsx flag in your components.json file.
{
"style": "default",
"tailwind": {
"config": "tailwind.config.js",
"css": "src/app/globals.css",
"baseColor": "zinc",
"cssVariables": true
},
"rsc": false,
"tsx": false,
"aliases": {
"utils": "~/lib/utils",
"components": "~/components"
}
}To configure import aliases, you can use the following jsconfig.json:
{
"compilerOptions": {
"paths": {
"@/*": ["./*"]
}
}
}Apps V4 Content Docs Changelog 2023 12 New Components (`apps/v4/content/docs/changelog/2023-12-new-components.mdx`)
title: December 2023 - New Components date: 2023-12-22
We've added new components to shadcn/ui and made a lot of improvements to the CLI.
Here's a quick overview of what's new:
- Carousel - A carousel component with motion, swipe gestures and keyboard support.
- Drawer - A drawer component that looks amazing on mobile.
- Pagination - A pagination component with page navigation, previous and next buttons.
- Resizable - A resizable component for building resizable panel groups and layouts.
- Sonner - The last toast component you'll ever need.
- CLI updates - Support for custom Tailwind prefix and
tailwind.config.ts.
Carousel
We've added a fully featured carousel component with motion, swipe gestures and keyboard support. Built on top of Embla Carousel.
It has support for infinite looping, autoplay, vertical orientation, and more.
Drawer
Oh the drawer component. Built on top of Vaul by emilkowalski.
Try opening the following drawer on mobile. It looks amazing!
Pagination
We've added a pagination component with page navigation, previous and next buttons. Simple, flexible and works with your framework's <Link /> component.
Resizable
Build resizable panel groups and layouts with this <Resizable /> component.
<Resizable /> is built using react-resizable-panels by bvaughn. It has support for mouse, touch and keyboard.
Sonner
Another one by emilkowalski. The last toast component you'll ever need. Sonner is now available in shadcn/ui.
CLI updates
This has been one of the most requested features. You can now configure a custom Tailwind prefix and the cli will automatically prefix your utility classes when adding components.
This means you can now easily add shadcn/ui components to existing projects like Docusaurus, Nextra...etc. A drop-in for your existing design system with no conflict.
<AlertDialog className="tw-grid tw-gap-4 tw-border tw-bg-background tw-shadow-lg" />It works with cn, cva and CSS variables.
The cli can now also detect tailwind.config.ts and add the TypeScript version of the config for you.
That's it. Happy Holidays.
Apps V4 Content Docs Changelog 2024 03 Blocks (`apps/v4/content/docs/changelog/2024-03-blocks.mdx`)
title: March 2024 - Introducing Blocks date: 2024-03-22
One of the most requested features since launch has been layouts: admin dashboards with sidebar, marketing page sections, cards and more.
Today, we're launching Blocks.
View the blocks library
Blocks are ready-made components that you can use to build your apps. They are fully responsive, accessible, and composable, meaning they are built using the same principles as the rest of the components in shadcn/ui.
We're starting with dashboard layouts and authentication pages, with plans to add more blocks in the coming weeks.
Open Source
Blocks are open source. You can find the source on GitHub. Use them in your projects, customize them and contribute back.
View the blocks library
Request a Block
We're also introducing a "Request a Block" feature. If there's a specific block you'd like to see, simply create a request on GitHub and the community can upvote and build it.
View the blocks library
v0
If you have a v0 account, you can use the Edit in v0 feature to open the code on v0 for prompting and further generation.
<svg
viewBox="0 0 40 20"
fill="none"
xmlns="http://www.w3.org/2000/svg"
className="h-40 w-40 text-foreground"
That's it. Looking forward to seeing what you build with Blocks.
Apps V4 Content Docs Changelog 2024 03 Breadcrumb Otp (`apps/v4/content/docs/changelog/2024-03-breadcrumb-otp.mdx`)
title: March 2024 - Breadcrumb and Input OTP date: 2024-03-08
We've added a new Breadcrumb component and an Input OTP component.
Breadcrumb
An accessible and flexible breadcrumb component. It has support for collapsed items, custom separators, bring-your-own routing <Link /> and composable with other shadcn/ui components.
Input OTP
A fully featured input OTP component. It has support for numeric and alphanumeric codes, custom length, copy-paste and accessible. Input OTP is built on top of input-otp by @guilherme_rodz.
If you have a v0 account, the new components are available for generation.
Apps V4 Content Docs Changelog 2024 04 Lift Mode (`apps/v4/content/docs/changelog/2024-04-lift-mode.mdx`)
title: April 2024 - Lift Mode date: 2024-04-05
We're introducing a new mode for Blocks called Lift Mode.
Enable Lift Mode to automatically "lift" smaller components from a block template for copy and paste.
View the blocks library
With Lift Mode, you'll be able to copy the smaller components that make up a block template, like cards, buttons, and forms, and paste them directly into your project.
Visit the Blocks page to try it out.
Apps V4 Content Docs Changelog 2024 08 Npx Shadcn Init (`apps/v4/content/docs/changelog/2024-08-npx-shadcn-init.mdx`)
title: August 2024 - npx shadcn init date: 2024-08-31
The new CLI is now available. It's a complete rewrite with a lot of new features and improvements. You can now install components, themes, hooks, utils and more using npx shadcn add.
This is a major step towards distributing code that you and your LLMs can access and use.
- First up, the CLI now has support for all major React frameworks out of the box. Next.js, Remix, Vite and Laravel. And when you init into a new app, we update your existing Tailwind files instead of overriding.
- A component now ships its own dependencies. Take the accordion for example, it can define its Tailwind keyframes. When you add it to your project, we'll update your tailwind.config.ts file accordingly.
- You can also install remote components using url.
npx shadcn add https://acme.com/registry/navbar.json. - We have also improved the init command. It does framework detection and can even init a brand new Next.js app in one command.
npx shadcn init. - We have created a new schema that you can use to ship your own component registry. And since it has support for urls, you can even use it to distribute private components.
- And a few more updates like better error handling and monorepo support.
You can try the new cli today.
npx shadcn init sidebar-01 login-01Update Your Project
To update an existing project to use the new CLI, update your components.json file to include import aliases for your components, utils, ui, lib and hooks.
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"tailwind": {
// ...
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
}
}If you're using a different import alias prefix, e.g. ~, replace @ with your prefix.
Apps V4 Content Docs Changelog 2024 10 React 19 (`apps/v4/content/docs/changelog/2024-10-react-19.mdx`)
title: October 2024 - React 19 date: 2024-10-29
shadcn/ui is now compatible with React 19 and Next.js 15.
We published a guide to help you upgrade your project to React 19.
Read more here.
Apps V4 Content Docs Changelog 2024 10 Sidebar (`apps/v4/content/docs/changelog/2024-10-sidebar.mdx`)
title: October 2024 - Sidebar date: 2024-10-18
Introducing sidebar.tsx: 25 components to help you build all kinds of sidebars.
I don't like building sidebars. So I built 30+ of them. All types. Then simplified the core into sidebar.tsx: a strong foundation to build on top of.
It works with Next.js, Remix, Vite & Laravel.
See the announcement here.
Apps V4 Content Docs Changelog 2024 11 Icons (`apps/v4/content/docs/changelog/2024-11-icons.mdx`)
title: November 2024 - Icons date: 2024-11-06
An update on icons. The new-york style now uses Lucide as the default icon set.
- New projects will use Lucide by default
- No breaking changes for existing projects
- Use the CLI to (optionally) migrate primitives to Lucide
For more info on why we're doing this, see the thread.
Apps V4 Content Docs Changelog 2024 12 Monorepo (`apps/v4/content/docs/changelog/2024-12-monorepo.mdx`)
title: December 2024 - Monorepo Support date: 2024-12-20
Until now, using shadcn/ui in a monorepo was a bit of a pain. You could add
components using the CLI, but you had to manage where the components
were installed and manually fix import paths.
With the new monorepo support in the CLI, we've made it a lot easier to use
shadcn/ui in a monorepo.
The CLI now understands the monorepo structure and will install the components,
dependencies and registry dependencies to the correct paths and handle imports
for you.
Read more in the docs.
Apps V4 Content Docs Changelog 2025 01 Blocks (`apps/v4/content/docs/changelog/2025-01-blocks.mdx`)
title: January 2025 - Blocks Community date: 2025-01-14
We are inviting the community to contribute to the blocks library. Share your components and blocks with other developers and help build a library of high-quality, reusable components.
We'd love to see all types of blocks: applications, marketing, products, and more.
See the docs page to get started.
Apps V4 Content Docs Changelog 2025 02 Registry Schema (`apps/v4/content/docs/changelog/2025-02-registry-schema.mdx`)
title: February 2025 - Updated Registry Schema date: 2025-02-06
We're updating the registry schema to support more features.
Define code as a flat JSON file and distribute it via the CLI.
- Custom styles: bring your own design system, components & tokens
- Extend, override, mix & match components from third-party registries and LLMs
- Install themes, CSS vars, hooks, animations, and Tailwind layers & utilities
Apps V4 Content Docs Changelog 2025 02 Tailwind V4 (`apps/v4/content/docs/changelog/2025-02-tailwind-v4.mdx`)
title: February 2025 - Tailwind v4 date: 2025-02-19
We shipped the first preview of Tailwind v4 and React 19. Ready for you to try out. You can start using it today.
What's New:
- The CLI can now initialize projects with Tailwind v4.
- Full support for the new @theme directive and @theme inline option.
- All components are updated for Tailwind v4 and React 19.
- We've removed the forwardRefs and adjusted the types.
- Every primitive now has a data-slot attribute for styling.
- We've fixed and cleaned up the style of the components.
- We're deprecating the toast component in favor of sonner.
- Buttons now use the default cursor.
- We're deprecating the default style. New projects will use new-york.
- HSL colors are now converted to OKLCH.
Read more in the docs.
Apps V4 Content Docs Changelog 2025 04 Cross Framework (`apps/v4/content/docs/changelog/2025-04-cross-framework.mdx`)
title: April 2025 - Cross-framework Route Support date: 2025-04-09
The shadcn CLI can now auto-detect your framework and adapt routes for you.
Works with all frameworks including Laravel, Vite and React Router.
Apps V4 Content Docs Changelog 2025 04 Mcp (`apps/v4/content/docs/changelog/2025-04-mcp.mdx`)
title: April 2025 - MCP date: 2025-04-30
We're working on zero-config MCP support for shadcn/ui registry. One command npx shadcn registry:mcp to make any registry mcp-compatible.
Learn more in the thread here.
Apps V4 Content Docs Changelog 2025 04 Shadcn 2 5 (`apps/v4/content/docs/changelog/2025-04-shadcn-2-5.mdx`)
title: April 2025 - shadcn 2.5.0 date: 2025-04-26
We tagged shadcn 2.5.0 earlier this week. It comes with a pretty cool feature: resolve anywhere.
Registries can now place files anywhere in an app and we'll properly resolve imports. No need to stick to a fixed file structure. It can even add files outside the registry itself.
On install, we track all files and perform a multi-pass resolution to correctly handle imports and aliases. It's fast.
Apps V4 Content Docs Changelog 2025 05 New Site (`apps/v4/content/docs/changelog/2025-05-new-site.mdx`)
title: May 2025 - New Site date: 2025-05-30
We've upgraded ui.shadcn.com to Next.js 15.3 and Tailwind v4. The site now uses the upgraded new-york components.
We've also made some minor design updates to make the site faster and easier to navigate.
This upgrade unlocks a lot of new features that we're working on. More to come.
Apps V4 Content Docs Changelog 2025 06 Calendar (`apps/v4/content/docs/changelog/2025-06-calendar.mdx`)
title: June 2025 - Calendar Component date: 2025-06-06
We've upgraded the Calendar component to the latest version of React DayPicker.
This is a major upgrade and includes a lot of new features and improvements.
To upgrade your project to the latest version of the Calendar component, see the upgrade guide.
Apps V4 Content Docs Changelog 2025 06 Radix Ui (`apps/v4/content/docs/changelog/2025-06-radix-ui.mdx`)
title: June 2025 - radix-ui Migration date: 2025-06-11
We've added a new command to migrate to the new radix-ui package. This command will replace all @radix-ui/react-* imports with radix-ui.
npx shadcn@latest migrate radixIt will automatically update all imports in your ui components and install radix-ui as a dependency.
- import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog"
+ import { AlertDialog as AlertDialogPrimitive } from "radix-ui"Make sure to test your components and project after running the command.
Note: To update imports for newly added components, run the migration command again.
Apps V4 Content Docs Changelog 2025 07 Local File Support (`apps/v4/content/docs/changelog/2025-07-local-file-support.mdx`)
title: July 2025 - Local File Support date: 2025-07-07
The shadcn CLI now supports local files. Initialize projects and add components, themes, hooks, utils and more from local JSON files.
# Initialize a project from a local file
npx shadcn init ./template.json
# Add a component from a local file
npx shadcn add ./block.jsonThis feature enables powerful new workflows:
- Zero setup - No remote registries required
- Faster development - Test registry items locally before publishing
- Enhanced workflow for agents and MCP - Generate and run registry items locally
- Private components - Keep proprietary components local and private.
Apps V4 Content Docs Changelog 2025 07 Universal Registry (`apps/v4/content/docs/changelog/2025-07-universal-registry.mdx`)
title: July 2025 - Universal Registry Items date: 2025-07-11
We've added support for universal registry items. This allows you to create registry items that can be distributed to any project i.e. no framework, no components.json, no tailwind, no react required.
This new registry item type unlocks a lot of new workflows. You can now distribute code, config, rules, docs, anything to any code project.
See the docs for more details and examples.
Apps V4 Content Docs Changelog 2025 08 Cli 3 Mcp (`apps/v4/content/docs/changelog/2025-08-cli-3-mcp.mdx`)
title: August 2025 - shadcn CLI 3.0 and MCP Server date: 2025-08-27
We just shipped shadcn CLI 3.0 with support for namespaced registries, advanced authentication, new commands and a completely rewritten registry engine.
What's New
- Namespaced Registries - Install components using
@registry/nameformat. - Private Registries - Secure your registry with advanced authentication.
- Search & Discovery - New commands to find and view code before installing.
- MCP Server - MCP server for all registries.
- Faster Everything - Completely rewritten registry resolution.
- Improved Error Handling - Better error messages for users and LLMs.
- Upgrade Guide - Migration notes for existing users.
Namespaced Registries
The biggest change in 3.0 is namespaced registries. You can now install components from registries: a community registry, your company's private registry or internal registry, using the @registry/name format.
This makes it easier to distribute code across teams and projects.
Configure registries in your components.json:
{
"registries": {
"@acme": "https://acme.com/r/{name}.json",
"@internal": {
"url": "https://registry.company.com/{name}",
"headers": {
"Authorization": "Bearer ${REGISTRY_TOKEN}"
}
}
}
}Then use the @registry/name format to install components:
npx shadcn add @acme/button @internal/auth-systemIt's completely decentralized. There's no central registrar. Create any namespace you want and organize components however makes sense for your team.
{
"registries": {
"@design": "https://registry.company.com/create/{name}.json",
"@engineering": "https://registry.company.com/eng/{name}.json",
"@marketing": "https://registry.company.com/marketing/{name}.json"
}
}Components can even depend on resources from different registries. Everything gets resolved and installed automatically from the right sources.
{
"name": "dashboard",
"type": "registry:block",
"registryDependencies": [
"@shadcn/card", // From default registry
"@v0/chart", // From v0 registry
"@acme/data-table", // From acme registry
"@lib/data-fetcher", // Utility library
"@ai/analytics-prompt" // AI prompt resource
]
}Private Registries
Need to keep your components private? We've got you covered. Configure authentication with tokens, API keys, or custom headers:
{
"registries": {
"@private": {
"url": "https://registry.company.com/{name}.json",
"headers": {
"Authorization": "Bearer ${REGISTRY_TOKEN}"
}
}
}
}Your private components stay private. Perfect for enterprise teams with proprietary UI libraries.
We support all major authentication methods: basic auth, bearer token, API key query params and custom headers.
See the authentication docs for more details.
Search & Discovery
Three new commands make it easy to find exactly what you need:
- View items from the registry before installing
npx shadcn view @acme/auth-system- Search items from registries
npx shadcn search @tweakcn -q "dark"- List all items from a registry
npx shadcn list @acmePreview components before installing them. Search across multiple registries. See the code and all dependencies upfront.
MCP Server
Back in April, we introduced the first version of the MCP server. Since then, we've taken everything we learned and built a better MCP server.
Here's what's new:
- Works with all registries. Zero config
- One command to add to your favorite MCP clients
- We improved the underlying tools
- Better integration with the CLI and registries
- Support for multiple registries in the same project
Add the MCP server to your project:
npx shadcn@latest mcp initSee the docs for more details.
Faster Everything
We completely rewrote the registry resolution engine from scratch. It's faster, smarter, and handles even the trickiest dependency trees.
- Up to 3x faster dependency resolution
- Smarter file deduplication and merging
- Better monorepo support out of the box
- Updated
buildcommand for registry authors
Improved Error Handling
Registry developers can now provide custom error messages to help guide users (and LLMs) when things go wrong. The CLI displays helpful, actionable errors for common issues:
Unknown registry "@acme". Make sure it is defined in components.json as follows:
{
"registries": {
"@acme": "[URL_TO_REGISTRY]"
}
}Missing environment variables? The CLI tells you exactly what's needed:
Registry "@private" requires the following environment variables:
• REGISTRY_TOKEN
Set the required environment variables in your .env or .env.local file.Registry authors can provide custom error messages in their responses to help users and AI agents understand and fix issues quickly.
Error:
You are not authorized to access the item at http://example.com/r/component.
Message:
[Unauthorized] Your API key has expired. Renew it at https://example.com/api/renew-key.Upgrade Guide
Here's the best part: there are no breaking changes for users. Your existing components.json works exactly the same. All your installed components work exactly the same.
For developers, if you're using the programmatic APIs directly, we've deprecated a few functions in favor of better ones:
fetchRegistry→getRegistryresolveRegistryTree→resolveRegistryItems- Schema moved from
shadcn/registrytoshadcn/schemapackage
- import { registryItemSchema } from "shadcn/registry"
+ import { registryItemSchema } from "shadcn/schema"That's it. Seriously. Everything else just works.
Apps V4 Content Docs Changelog 2025 10 New Components (`apps/v4/content/docs/changelog/2025-10-new-components.mdx`)
title: October 2025 - New Components date: 2025-10-03
For this round of components, I looked at what we build every day, the boring stuff we rebuild over and over, and made reusable abstractions you can actually use.
These components work with every component library, Radix, Base UI, React Aria, you name it. Copy and paste to your projects.
- Spinner: An indicator to show a loading state.
- Kbd: Display a keyboard key or group of keys.
- Button Group: A group of buttons for actions and split buttons.
- Input Group: Input with icons, buttons, labels and more.
- Field: One component. All your forms.
- Item: Display lists of items, cards, and more.
- Empty: Use this one for empty states.
Spinner
Okay let's start with the easiest ones: Spinner and Kbd. Pretty basic. We all know what they do.
Here's how you render a spinner:
import { Spinner } from "@/components/ui/spinner"<Spinner />Here's what it looks like:
<ComponentPreview
name="spinner-basic"
/>
Here's what it looks like in a button:
<ComponentPreview
name="spinner-button"
/>
You can edit the code and replace it with your own spinner.
<ComponentPreview
name="spinner-custom"
/>
Kbd
Kbd is a component that renders a keyboard key.
import { Kbd, KbdGroup } from "@/components/ui/kbd"<Kbd>Ctrl</Kbd>Use KbdGroup to group keyboard keys together.
<KbdGroup>
<Kbd>Ctrl</Kbd>
<Kbd>B</Kbd>
</KbdGroup><ComponentPreview
name="kbd-demo"
/>
You can add it to buttons, tooltips, input groups, and more.
Button Group
I got a lot of requests for this one: Button Group. It's a container that groups related buttons together with consistent styling. Great for action groups, split buttons, and more.
<ComponentPreview
name="button-group-demo"
/>
Here's the code:
import { ButtonGroup } from "@/components/ui/button-group"<ButtonGroup>
<Button>Button 1</Button>
<Button>Button 2</Button>
</ButtonGroup>You can nest button groups to create more complex layouts with spacing.
<ButtonGroup>
<ButtonGroup>
<Button>Button 1</Button>
<Button>Button 2</Button>
</ButtonGroup>
<ButtonGroup>
<Button>Button 3</Button>
<Button>Button 4</Button>
</ButtonGroup>
</ButtonGroup>Use ButtonGroupSeparator to create split buttons. Classic dropdown pattern.
<ComponentPreview
name="button-group-dropdown"
/>
You can also use it to add prefix or suffix buttons and text to inputs.
<ComponentPreview
name="button-group-select"
/>
<ButtonGroup>
<ButtonGroupText>Prefix</ButtonGroupText>
<Input placeholder="Type something here..." />
<Button>Button</Button>
</ButtonGroup>Input Group
Input Group lets you add icons, buttons, and more to your inputs. You know, all those little bits you always need around your inputs.
import {
InputGroup,
InputGroupAddon,
InputGroupInput,
} from "@/components/ui/input-group"<InputGroup>
<InputGroupInput placeholder="Search..." />
<InputGroupAddon>
<SearchIcon />
</InputGroupAddon>
</InputGroup>Here's a preview with icons:
You can also add buttons to the input group.
Or text, labels, tooltips, ...
It also works with textareas so you can build really complex components with lots of knobs and dials or yet another prompt form.
Oh here are some cool ones with spinners:
Field
Introducing Field, a component for building really complex forms. The abstraction here is beautiful.
It took me a long time to get it right but I made it work with all your form libraries: Server Actions, React Hook Form, TanStack Form, Bring Your Own Form.
import {
Field,
FieldDescription,
FieldError,
FieldLabel,
} from "@/components/ui/field"Here's a basic field with an input:
<Field>
<FieldLabel htmlFor="username">Username</FieldLabel>
<Input id="username" placeholder="Max Leiter" />
<FieldDescription>
Choose a unique username for your account.
</FieldDescription>
</Field>It works with all form controls. Inputs, textareas, selects, checkboxes, radios, switches, sliders, you name it. Here's a full example:
Here are some checkbox fields:
You can group fields together using FieldGroup and FieldSet. Perfect for
multi-section forms.
<FieldSet>
<FieldLegend />
<FieldGroup>
<Field />
<Field />
</FieldGroup>
</FieldSet>Making it responsive is easy. Use orientation="responsive" and it switches
between vertical and horizontal layouts based on container width. Done.
Wait, here's more. Wrap your fields in FieldLabel to create a selectable field group. Really easy. And it looks great.
Item
This one is a straightforward flex container that can house nearly any type of content.
I've built this so many times that I decided to create a component for it. Now I use it all the time. I use it to display lists of items, cards, and more.
import {
Item,
ItemContent,
ItemDescription,
ItemMedia,
ItemTitle,
} from "@/components/ui/item"Here's a basic item:
<Item>
<ItemMedia variant="icon">
<HomeIcon />
</ItemMedia>
<ItemContent>
<ItemTitle>Dashboard</ItemTitle>
<ItemDescription>Overview of your account and activity.</ItemDescription>
</ItemContent>
</Item>You can add icons, avatars, or images to the item.
And here's what a list of items looks like with ItemGroup:
Need it as a link? Use the asChild prop:
<Item asChild>
<a href="/dashboard">
<ItemMedia variant="icon">
<HomeIcon />
</ItemMedia>
<ItemContent>
<ItemTitle>Dashboard</ItemTitle>
<ItemDescription>Overview of your account and activity.</ItemDescription>
</ItemContent>
</a>
</Item>Empty
Okay last one: Empty. Use this to display empty states in your app.
import {
Empty,
EmptyContent,
EmptyDescription,
EmptyMedia,
EmptyTitle,
} from "@/components/ui/empty"Here's how you use it:
<Empty>
<EmptyMedia variant="icon">
<InboxIcon />
</EmptyMedia>
<EmptyTitle>No messages</EmptyTitle>
<EmptyDescription>You don't have any messages yet.</EmptyDescription>
<EmptyContent>
<Button>Send a message</Button>
</EmptyContent>
</Empty>You can use it with avatars:
Or with input groups for things like search results or email subscriptions:
That's it. Seven new components. Works with all your libraries. Ready for your projects.
Apps V4 Content Docs Changelog 2025 10 Registry Directory (`apps/v4/content/docs/changelog/2025-10-registry-directory.mdx`)
title: October 2025 - Registry Directory date: 2025-10-28
We just published the Registry Directory: a list of code registries you can browse and pull code and components from.
https://ui.shadcn.com/docs/directory
Built into the CLI. No config required.
Apps V4 Content Docs Changelog 2025 12 Shadcn Create (`apps/v4/content/docs/changelog/2025-12-shadcn-create.mdx`)
title: December 2025 - npx shadcn create date: 2025-12-12
From the very first commit, the goal of shadcn/ui was to make it customizable.
The idea is to give you solid defaults, spacing, color tokens, animations, accessibility, and then let you take it from there. Tweak the code. Add new components. Change the colors. Build your own version.
But somewhere along the way, all apps started looking the same. I guess the defaults were a little too good. My bad.
Today, we're changing that: npx shadcn create.
Customize Everything. Pick your component library, icons, base color, theme, fonts and create your own version of shadcn/ui.
We're starting with 5 new visual styles, designed to help your UI actually feel like your UI.
- Vega – The classic shadcn/ui look.
- Nova – Reduced padding and margins for compact layouts.
- Maia – Soft and rounded, with generous spacing.
- Lyra – Boxy and sharp. Pairs well with mono fonts.
- Mira – Compact. Made for dense interfaces.
This goes beyond theming.
Your config doesn't just change colors, it rewrites the component code to match your setup. Fonts, spacing, structure, even the libraries you use, everything adapts to your preferences.
The new CLI takes care of it all.
Start with a component library. Choose between Radix or Base UI.
We rebuilt every component for Base UI, keeping the same abstraction.
They are fully compatible with your existing components, even those pulled from remote registries.
When you pull down components, we auto-detect your library and apply the right transformations.
It's time to build something that doesn't look like everything else.
Now available for Next.js, Vite, TanStack Start and v0.
Get StartedApps V4 Content Docs Changelog 2026 01 Base Ui (`apps/v4/content/docs/changelog/2026-01-base-ui.mdx`)
title: January 2026 - Base UI Documentation date: 2026-01-20
We've shipped full documentation for Base UI components.
When we launched npx shadcn create in December, we introduced the ability to choose between Radix and Base UI as your component library. Today, we're following up with complete documentation for all Base UI components.
What's New
- Full Base UI docs - Every component now has dedicated documentation for Base UI, covering usage, props, and examples.
- Rebuilt examples - All component examples have been rebuilt for both Radix and Base UI. Switch between them to see the implementation differences.
- Side-by-side comparison - The docs make it easy to compare how components work across both libraries.
Same Abstraction, Different Primitives
The goal remains the same: give you a consistent API regardless of which primitive library you choose. The components look and behave the same way. Only the underlying implementation changes.
// Works the same whether you're using Radix or Base UI.
import { Dialog, DialogContent, DialogTrigger } from "@/components/ui/dialog"If you're starting a new project, run npx shadcn create and pick your preferred library. The CLI handles the rest.
Apps V4 Content Docs Changelog 2026 01 Inline Side Styles (`apps/v4/content/docs/changelog/2026-01-inline-side-styles.mdx`)
title: January 2026 - Inline Start and End Styles date: 2026-01-23
We've updated the styles for Base UI components to support inline-start and inline-end side values. The following components now support these values:
- Tooltip
- Popover
- Combobox
- Context Menu
- Dropdown Menu
- Hover Card
- Menubar
- Select
What Changed
We added new Tailwind classes to handle the logical side values:
<PopoverPrimitive.Popup
className={cn(
"... data-[side=bottom]:slide-in-from-top-2
data-[side=left]:slide-in-from-right-2
data-[side=right]:slide-in-from-left-2
data-[side=top]:slide-in-from-bottom-2
+ data-[side=inline-start]:slide-in-from-right-2
+ data-[side=inline-end]:slide-in-from-left-2 ...",
className
)}
/>Usage
<Popover>
<PopoverTrigger>Open</PopoverTrigger>
<PopoverContent side="inline-start">
{/* Opens on the left in LTR, right in RTL */}
</PopoverContent>
</Popover>LLM Prompt
Ask your LLM to update your components by running the following prompt:
/* Detailed source-code truncated for AI context efficiency. */Apps V4 Content Docs Changelog 2026 01 Rtl (`apps/v4/content/docs/changelog/2026-01-rtl.mdx`)
title: January 2026 - RTL Support date: 2026-01-28
shadcn/ui now has first-class support for right-to-left (RTL) layouts. Your components automatically adapt for languages like Arabic, Hebrew, and Persian.
This works with the shadcn/ui components as well as any component distributed on the shadcn registry.
Our approach to RTL
Traditionally, component libraries that support RTL ship with logical classes baked in. This means everyone has to work with classes like ms-4 and start-2, even if they're only building for LTR layouts.
We took a different approach. The shadcn CLI transforms classes at install time, so you only see logical classes when you actually need them. If you're not building for RTL, you work with familiar classes like ml-4 and left-2. When you enable RTL, the CLI handles the conversion for you.
You don't have to learn RTL until you need it.
How it works
When you add components with rtl: true set in your components.json, the CLI automatically converts physical CSS classes like ml-4 and text-left to their logical equivalents like ms-4 and text-start.
- Physical positioning classes like
left-*andright-*becomestart-*andend-*. - Margin and padding classes like
ml-*andpr-*becomems-*andpe-*. - Text alignment classes like
text-leftbecometext-start. - Directional props are updated to use logical values.
- Supported icons are automatically flipped using
rtl:rotate-180. - Animations like
slide-in-from-leftbecomeslide-in-from-start.
RTL examples for every component
We've added RTL examples for every component. You'll find live previews and code on each component page.
CLI updates
New projects: Use the --rtl flag with init or create to enable RTL from the start.
npx shadcn@latest init --rtlnpx shadcn@latest create --rtlExisting projects: Migrate your components with the migrate rtl command.
npx shadcn@latest migrate rtlThis transforms all components in your ui directory to use logical classes. You can also pass a specific path or glob pattern.
Try it out
Click the link below to open a Next.js project with RTL support in v0.
Links
- RTL Documentation
- Font Recommendations
- Animations
- Migrating Existing Components
- Next.js Setup
- Vite Setup
- TanStack Start Setup
Apps V4 Content Docs Changelog 2026 02 Blocks (`apps/v4/content/docs/changelog/2026-02-blocks.mdx`)
title: February 2026 - Blocks for Radix and Base UI date: 2026-02-06
All blocks are now available for both Radix and Base UI.
- All blocks for both libraries - Every block, including login, signup, sidebar and dashboard blocks, is now available in both Radix and Base UI variants.
- Same CLI workflow - Run
npx shadcn addand the CLI will pull the correct block variant based on your project configuration.
If you've already set up your project with npx shadcn create, blocks will automatically use your chosen library. No additional configuration needed.
npx shadcn@latest add login-01Browse the full collection on the blocks page.
Apps V4 Content Docs Changelog 2026 02 Radix Ui (`apps/v4/content/docs/changelog/2026-02-radix-ui.mdx`)
title: February 2026 - Unified Radix UI Package date: 2026-02-02
The new-york style now uses the unified radix-ui package instead of individual @radix-ui/react-* packages.
What's Changed
When you add components using the new-york style, they will now import from radix-ui instead of separate packages:
- import * as DialogPrimitive from "@radix-ui/react-dialog"
+ import { Dialog as DialogPrimitive } from "radix-ui"This results in a cleaner package.json with a single radix-ui dependency instead of multiple @radix-ui/react-* packages.
Migrating Existing Projects
If you have an existing project using the new-york style, you can migrate to the new radix-ui package using the migrate command:
npx shadcn@latest migrate radixThis will update all imports in your UI components and add radix-ui to your dependencies.
To migrate components outside of your ui directory, use the path argument:
npx shadcn@latest migrate radix src/components/customOnce complete, you can remove any unused @radix-ui/react-* packages from your package.json.
See the migrate radix documentation for more details.
Apps V4 Content Docs Changelog 2026 03 Cli V4 (`apps/v4/content/docs/changelog/2026-03-cli-v4.mdx`)
title: March 2026 - shadcn/cli v4 date: 2026-03-06
We're releasing version 4 of shadcn/cli. More capable, easier to use. Built for you and your coding agents. Here's everything new.
shadcn/skills
shadcn/skills gives coding agents the context they need to work with your components and registry correctly. It covers both Radix and Base UI primitives, updated APIs, component patterns and registry workflows. The skill also knows how to use the shadcn CLI, when to invoke it and which flags to pass. Agents make fewer mistakes and produce code that actually matches your design system.
You can ask your agent things like:
- "create a new vite monorepo"
- "find me a hero from tailark, add it to the homepage, animate the text using an animation from react-bits"
- "install and configure a sign in page from @clerk"
npx skills add shadcn/uiIntroducing --preset
A preset packs your entire design system config into a short code. Colors, theme, icon library, fonts, radius. One string, everything included.
Build your preset on shadcn/create, preview it live and grab the code when you're ready.
npx shadcn@latest init --preset a1Dg5eFlUse it to scaffold projects from custom config, share with your team or publish in your registry. Drop it in prompts so your agent knows where to start. Use it across Claude, Codex, v0, Replit. Take your preset with you.
Switching presets
When you're working on a new app, it can take a few tries to find something you like so we've made switching presets really easy. Run init --preset in your app, and the CLI will take care of reconfiguring everything, including your components.
npx shadcn@latest init --preset ad3qkJ7Skills + Presets
Your agent knows how to use presets. Scaffold a project, switch design systems, try something new.
- "create a new next app using --preset adtk27v"
- "let's try --preset adtk27v"
New shadcn/create
To help you build custom presets, we rebuilt shadcn/create. It now includes a library of UI components you can use to preview your presets. See how your colors, fonts and radius apply to real components before you start building.
New --dry-run, --diff, and --view flags
Inspect what a registry will add to your project before anything gets written. Review the payload yourself or pipe it to your coding agent for a second look.
npx shadcn@latest add button --dry-run
npx shadcn@latest add button --diff
npx shadcn@latest add button --viewUpdating primitives
You can use the --diff flag to check for registry updates. Or ask your agent: "check for updates from @shadcn and merge with my local changes".
npx shadcn@latest add button --diffshadcn init --template
shadcn init now scaffolds full project templates for Next.js, Vite, Laravel, React Router, Astro and TanStack Start. Dark mode included for Next.js and Vite.
npx shadcn@latest init
Select a template › - Use arrow-keys. Return to submit.
❯ Next.js
Vite
TanStack Start
React Router
Astro
LaravelUse --monorepo to set up a monorepo.
npx shadcn@latest init -t next --monoreposhadcn init --base
Pick your primitives. Use --base to start a project with Radix or Base UI.
npx shadcn@latest init --base radixshadcn info
The info command now shows the full picture: framework, version, CSS vars, which components are installed, and where to find docs and examples for every component. Great for giving coding agents the context they need to work with your project.
npx shadcn@latest infoshadcn docs
Get docs, code and examples for any UI component right from the CLI. Gives your coding agent the context to use your primitives correctly.
npx shadcn@latest docs combobox
combobox
- docs https://ui.shadcn.com/docs/components/radix/combobox
- examples https://raw.githubusercontent.com/shadcn-ui/ui/refs/heads/main/apps/v4/registry/bases/radix/examples/combobox-example.tsx
- api https://base-ui.com/react/components/comboboxregistry:base and registry:font
Registries can now distribute an entire design system as a single payload using registry:base. Components, dependencies, CSS vars, fonts, config. One install, everything set up.
Fonts are now a first-class registry type. Install and configure them the same way you install components.
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "font-inter",
"type": "registry:font",
"font": {
"family": "'Inter Variable', sans-serif",
"provider": "google",
"import": "Inter",
"variable": "--font-sans",
"subsets": ["latin"]
}
}npx shadcn@latest add font-interLinks
Apps V4 Content Docs Changelog 2026 03 Luma (`apps/v4/content/docs/changelog/2026-03-luma.mdx`)
title: March 2026 - Introducing Luma date: 2026-03-31
Introducing Luma, a new shadcn/ui style. Rounded geometry. Soft elevation. Breathable layouts. Inspired by macOS Tahoe, minus the glass.
Try Luma in shadcn/create
Luma is a new foundation for your next app. It gives components softer surfaces, more open spacing, and a calmer visual rhythm while keeping the same shadcn/ui workflow.
Like the other new styles, Luma goes beyond theming. It changes the geometry, spacing, and feel of the components so your app starts from a different visual baseline.
Available now in shadcn/create for both Radix and Base UI.
Try LumaApps V4 Content Docs Changelog 2026 04 Component Composition (`apps/v4/content/docs/changelog/2026-04-component-composition.mdx`)
title: April 2026 - Component Composition date: 2026-04-06
We've added Composition sections across the component docs so you can see the correct structure at a glance: what wraps what, which subcomponents belong together, and how to avoid invalid nesting.
Card
├── CardHeader
│ ├── CardTitle
│ ├── CardDescription
│ └── CardAction
├── CardContent
└── CardFooterWhy we added this
We've found that LLMs and coding agents compose elements more reliably when they can see the full structure: fewer missing wrappers, fewer wrong hierarchies, better matches to the examples.
Bring docs into your agent
You or your LLM can pull the same component documentation, including composition, usage, and examples, into context from the CLI:
npx shadcn@latest docs cardIf you're using the shadcn/skills, this is done automatically for you.
Apps V4 Content Docs Changelog 2026 04 Sera (`apps/v4/content/docs/changelog/2026-04-sera.mdx`)
title: April 2026 - Introducing Sera date: 2026-04-16
Introducing Sera, a new shadcn/ui style. Minimal. Editorial. Typographic. Underline Controls and Uppercase Headings. Shaped by Print Design Principles.
Try Sera in shadcn/create
Sera is a typography-first style built on print design principles. It pairs serif headings with sans-serif body text, uses square corners, uppercase tracking, and underlined controls to create an editorial feel for your app.
Like the other new styles, Sera goes beyond theming. It changes the geometry, spacing, and feel of the components so your app starts from a different visual baseline.
Available now in shadcn/create for both Radix and Base UI.
Try SeraApps V4 Content Docs Changelog 2026 04 Shadcn Apply (`apps/v4/content/docs/changelog/2026-04-shadcn-apply.mdx`)
title: April 2026 - shadcn apply date: 2026-04-08
We added shadcn apply so you can switch presets in an existing project without starting over.
When you run npx shadcn@latest apply in an existing project, we apply a new preset, reinstall your existing components, and update your theme, colors, CSS variables, fonts, and icons.
npx shadcn@latest apply --preset b2D0vQ7G4The CLI keeps the current base and RTL settings from your existing project, even when the preset URL was generated with different values.
Try a PresetApps V4 Content Docs Dark Mode Astro (`apps/v4/content/docs/dark-mode/astro.mdx`)
title: Astro
Create an inline theme script
---
import '../styles/globals.css'
---
<script is:inline>
const getThemePreference = () => {
if (typeof localStorage !== 'undefined' && localStorage.getItem('theme')) {
return localStorage.getItem('theme');
}
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
};
const isDark = getThemePreference() === 'dark';
document.documentElement.classList[isDark ? 'add' : 'remove']('dark');
if (typeof localStorage !== 'undefined') {
const observer = new MutationObserver(() => {
const isDark = document.documentElement.classList.contains('dark');
localStorage.setItem('theme', isDark ? 'dark' : 'light');
});
observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class'] });
}
</script>
<html lang="en">
<body>
<h1>Astro</h1>
</body>
</html>Add a mode toggle
/* Detailed source-code truncated for AI context efficiency. */Display the mode toggle
Place a mode toggle on your site to toggle between light and dark mode.
---
import '../styles/globals.css'
import { ModeToggle } from '@/components/ModeToggle';
---
<html lang="en">
<body>
<h1>Astro</h1>
<ModeToggle client:load />
</body>
</html>Apps V4 Content Docs Dark Mode Meta.Json (`apps/v4/content/docs/dark-mode/meta.json`)
{
"title": "Dark mode",
"pages": ["index", "next", "vite", "astro", "remix"]
}
Apps V4 Content Docs Dark Mode Next (`apps/v4/content/docs/dark-mode/next.mdx`)
title: Next.js
Install next-themes
Start by installing next-themes:
npm install next-themesCreate a theme provider
"use client"
import * as React from "react"
import { ThemeProvider as NextThemesProvider } from "next-themes"
export function ThemeProvider({
children,
...props
}: React.ComponentProps<typeof NextThemesProvider>) {
return <NextThemesProvider {...props}>{children}</NextThemesProvider>
}Wrap your root layout
Add the ThemeProvider to your root layout and add the suppressHydrationWarning prop to the html tag.
import { ThemeProvider } from "@/components/theme-provider"
export default function RootLayout({ children }: RootLayoutProps) {
return (
<>
<html lang="en" suppressHydrationWarning>
<head />
<body>
<ThemeProvider
attribute="class"
defaultTheme="system"
enableSystem
disableTransitionOnChange
>
{children}
</ThemeProvider>
</body>
</html>
</>
)
}Add a mode toggle
Place a mode toggle on your site to toggle between light and dark mode.
Apps V4 Content Docs Dark Mode Remix (`apps/v4/content/docs/dark-mode/remix.mdx`)
title: Remix
Modify your tailwind.css file
Add :root[class~="dark"] to your tailwind.css file. This will allow you to use the dark class on your html element to apply dark mode styles.
.dark,
:root[class~="dark"] {
...;
}Install remix-themes
Start by installing remix-themes:
npm install remix-themesCreate a session storage and theme session resolver
import { createThemeSessionResolver } from "remix-themes"
// You can default to 'development' if process.env.NODE_ENV is not set
const isProduction = process.env.NODE_ENV === "production"
const sessionStorage = createCookieSessionStorage({
cookie: {
name: "theme",
path: "/",
httpOnly: true,
sameSite: "lax",
secrets: ["s3cr3t"],
// Set domain and secure only if in production
...(isProduction
? { domain: "your-production-domain.com", secure: true }
: {}),
},
})
export const themeSessionResolver = createThemeSessionResolver(sessionStorage)Set up Remix Themes
Add the ThemeProvider to your root layout.
import clsx from "clsx"
import { PreventFlashOnWrongTheme, ThemeProvider, useTheme } from "remix-themes"
import { themeSessionResolver } from "./sessions.server"
// Return the theme from the session storage using the loader
export async function loader({ request }: LoaderFunctionArgs) {
const { getTheme } = await themeSessionResolver(request)
return {
theme: getTheme(),
}
}
// Wrap your app with ThemeProvider.
// `specifiedTheme` is the stored theme in the session storage.
// `themeAction` is the action name that's used to change the theme in the session storage.
export default function AppWithProviders() {
const data = useLoaderData<typeof loader>()
return (
<ThemeProvider specifiedTheme={data.theme} themeAction="/action/set-theme">
<App />
</ThemeProvider>
)
}
export function App() {
const data = useLoaderData<typeof loader>()
const [theme] = useTheme()
return (
<html lang="en" className={clsx(theme)}>
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<Meta />
<PreventFlashOnWrongTheme ssrTheme={Boolean(data.theme)} />
<Links />
</head>
<body>
<Outlet />
<ScrollRestoration />
<Scripts />
<LiveReload />
</body>
</html>
)
}Add an action route
Create a file in /routes/action.set-theme.ts. Ensure that you pass the filename to the ThemeProvider component. This route is used to store the preferred theme in the session storage when the user changes it.
import { createThemeAction } from "remix-themes"
import { themeSessionResolver } from "./sessions.server"
export const action = createThemeAction(themeSessionResolver)Add a mode toggle
Place a mode toggle on your site to toggle between light and dark mode.
import { Moon, Sun } from "lucide-react"
import { Theme, useTheme } from "remix-themes"
import { Button } from "./ui/button"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "./ui/dropdown-menu"
export function ModeToggle() {
const [, setTheme] = useTheme()
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon">
<Sun className="h-[1.2rem] w-[1.2rem] scale-100 rotate-0 transition-all dark:scale-0 dark:-rotate-90" />
<Moon className="absolute h-[1.2rem] w-[1.2rem] scale-0 rotate-90 transition-all dark:scale-100 dark:rotate-0" />
<span className="sr-only">Toggle theme</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => setTheme(Theme.LIGHT)}>
Light
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setTheme(Theme.DARK)}>
Dark
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)
}Apps V4 Content Docs Dark Mode Vite (`apps/v4/content/docs/dark-mode/vite.mdx`)
title: Vite
Create a theme provider
/* Detailed source-code truncated for AI context efficiency. */Wrap your root layout
Add the ThemeProvider to your root layout.
import { ThemeProvider } from "@/components/theme-provider"
function App() {
return (
<ThemeProvider defaultTheme="dark" storageKey="vite-ui-theme">
{children}
</ThemeProvider>
)
}
export default AppAdd a mode toggle
Place a mode toggle on your site to toggle between light and dark mode.
import { Moon, Sun } from "lucide-react"
import { Button } from "@/components/ui/button"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { useTheme } from "@/components/theme-provider"
export function ModeToggle() {
const { setTheme } = useTheme()
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="icon">
<Sun className="h-[1.2rem] w-[1.2rem] scale-100 rotate-0 transition-all dark:scale-0 dark:-rotate-90" />
<Moon className="absolute h-[1.2rem] w-[1.2rem] scale-0 rotate-90 transition-all dark:scale-100 dark:rotate-0" />
<span className="sr-only">Toggle theme</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => setTheme("light")}>
Light
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setTheme("dark")}>
Dark
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setTheme("system")}>
System
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)
}Apps V4 Content Docs Forms Meta.Json (`apps/v4/content/docs/forms/meta.json`)
{
"pages": ["react-hook-form", "tanstack-form"]
}
Apps V4 Content Docs Forms Next (`apps/v4/content/docs/forms/next.mdx`)
title: Next.js
import { InfoIcon } from "lucide-react"
In this guide, we will take a look at building forms with Next.js using useActionState and Server Actions. We'll cover building forms, validation, pending states, accessibility, and more.
Demo
We are going to build the following form with a simple text input and a textarea. On submit, we'll use a server action to validate the form data and update the form state.
Approach
This form leverages Next.js and React's built-in capabilities for form handling. We'll build our form using the <Field /> component, which gives you complete flexibility over the markup and styling.
- Uses Next.js
<Form />component for navigation and progressive enhancement. <Field />components for building accessible forms.useActionStatefor managing form state and errors.- Handles loading states with the pending prop.
- Server Actions for handling form submissions.
- Server-side validation using Zod.
Anatomy
Here's a basic example of a form using the <Field /> component.
<Form action={formAction}>
<FieldGroup>
<Field data-invalid={!!formState.errors?.title?.length}>
<FieldLabel htmlFor="title">Bug Title</FieldLabel>
<Input
id="title"
name="title"
defaultValue={formState.values.title}
disabled={pending}
aria-invalid={!!formState.errors?.title?.length}
placeholder="Login button not working on mobile"
autoComplete="off"
/>
<FieldDescription>
Provide a concise title for your bug report.
</FieldDescription>
{formState.errors?.title && (
<FieldError>{formState.errors.title[0]}</FieldError>
)}
</Field>
</FieldGroup>
<Button type="submit">Submit</Button>
</Form>Usage
Create a form schema
We'll start by defining the shape of our form using a Zod schema in a schema.ts file.
import { z } from "zod"
export const formSchema = z.object({
title: z
.string()
.min(5, "Bug title must be at least 5 characters.")
.max(32, "Bug title must be at most 32 characters."),
description: z
.string()
.min(20, "Description must be at least 20 characters.")
.max(100, "Description must be at most 100 characters."),
})Define the form state type
Next, we'll create a type for our form state that includes values, errors, and success status. This will be used to type the form state on the client and server.
import { z } from "zod"
export type FormState = {
values?: z.infer<typeof formSchema>
errors: null | Partial<Record<keyof z.infer<typeof formSchema>, string[]>>
success: boolean
}Important: We define the schema and the FormState type in a separate file so we can import them into both the client and server components.
Create the Server Action
A server action is a function that runs on the server and can be called from the client. We'll use it to validate the form data and update the form state.
Note: We're returning values for error cases. This is because we want to keep the user submitted values in the form state. For success cases, we're returning empty values to reset the form.
Build the form
We can now build the form using the <Field /> component. We'll use the useActionState hook to manage the form state, server action, and pending state.
Done
That's it. You now have a fully accessible form with client and server-side validation.
When you submit the form, the formAction function will be called on the server. The server action will validate the form data and update the form state.
If the form data is invalid, the server action will return the errors to the client. If the form data is valid, the server action will return the success status and update the form state.
Pending States
Use the pending prop from useActionState to show loading indicators and disable form inputs.
"use client"
import * as React from "react"
import Form from "next/form"
import { Spinner } from "@/components/ui/spinner"
import { bugReportFormAction } from "./actions"
export function BugReportForm() {
const [formState, formAction, pending] = React.useActionState(
bugReportFormAction,
{
errors: null,
success: false,
}
)
return (
<Form action={formAction}>
<FieldGroup>
<Field data-disabled={pending}>
<FieldLabel htmlFor="name">Name</FieldLabel>
<Input id="name" name="name" disabled={pending} />
</Field>
<Field>
<Button type="submit" disabled={pending}>
{pending && <Spinner />} Submit
</Button>
</Field>
</FieldGroup>
</Form>
)
}Disabled States
Submit Button
To disable the submit button, use the pending prop on the button's disabled prop.
<Button type="submit" disabled={pending}>
{pending && <Spinner />} Submit
</Button>Field
To apply a disabled state and styling to a <Field /> component, use the data-disabled prop on the <Field /> component.
<Field data-disabled={pending}>
<FieldLabel htmlFor="name">Name</FieldLabel>
<Input id="name" name="name" disabled={pending} />
</Field>Validation
Server-side Validation
Use safeParse() on your schema in your server action to validate the form data.
"use server"
export async function bugReportFormAction(
_prevState: FormState,
formData: FormData
) {
const values = {
title: formData.get("title") as string,
description: formData.get("description") as string,
}
const result = formSchema.safeParse(values)
if (!result.success) {
return {
values,
success: false,
errors: result.error.flatten().fieldErrors,
}
}
return {
errors: null,
success: true,
}
}Business Logic Validation
You can add additional custom validation logic in your server action.
Make sure to return the values on validation errors. This is to ensure that the form state maintains the user's input.
"use server"
export async function bugReportFormAction(
_prevState: FormState,
formData: FormData
) {
const values = {
title: formData.get("title") as string,
description: formData.get("description") as string,
}
const result = formSchema.safeParse(values)
if (!result.success) {
return {
values,
success: false,
errors: result.error.flatten().fieldErrors,
}
}
// Check if email already exists in database.
const existingUser = await db.user.findUnique({
where: { email: result.data.email },
})
if (existingUser) {
return {
values,
success: false,
errors: {
email: ["This email is already registered"],
},
}
}
return {
errors: null,
success: true,
}
}Displaying Errors
Display errors next to the field using <FieldError />. Make sure to add the data-invalid prop to the <Field /> component and aria-invalid prop to the input.
<Field data-invalid={!!formState.errors?.email?.length}>
<FieldLabel htmlFor="email">Email</FieldLabel>
<Input
id="email"
name="email"
type="email"
aria-invalid={!!formState.errors?.email?.length}
/>
{formState.errors?.email && (
<FieldError>{formState.errors.email[0]}</FieldError>
)}
</Field>Resetting the Form
When you submit a form with a server action, React will automatically reset the form state to the initial values.
Reset on Success
To reset the form on success, you can omit the values from the server action and React will automatically reset the form state to the initial values. This is standard React behavior.
export async function demoFormAction(
_prevState: FormState,
formData: FormData
) {
const values = {
title: formData.get("title") as string,
description: formData.get("description") as string,
}
// Validation.
if (!result.success) {
return {
values,
success: false,
errors: result.error.flatten().fieldErrors,
}
}
// Business logic.
callYourDatabaseOrAPI(values)
// Omit the values on success to reset the form state.
return {
errors: null,
success: true,
}
}Preserve on Validation Errors
To prevent the form from being reset on failure, you can return the values in the server action. This is to ensure that the form state maintains the user's input.
export async function demoFormAction(
_prevState: FormState,
formData: FormData
) {
const values = {
title: formData.get("title") as string,
description: formData.get("description") as string,
}
// Validation.
if (!result.success) {
return {
// Return the values on validation errors.
values,
success: false,
errors: result.error.flatten().fieldErrors,
}
}
}Complex Forms
Here is an example of a more complex form with multiple fields and validation.
Schema
Form
Server Action
Apps V4 Content Docs Forms React Hook Form (`apps/v4/content/docs/forms/react-hook-form.mdx`)
title: React Hook Form links: doc: https://react-hook-form.com
import { InfoIcon } from "lucide-react"
In this guide, we will take a look at building forms with React Hook Form. We'll cover building forms with the <Field /> component, adding schema validation using Zod, error handling, accessibility, and more.
Demo
We are going to build the following form. It has a simple text input and a textarea. On submit, we'll validate the form data and display any errors.
Approach
This form leverages React Hook Form for performant, flexible form handling. We'll build our form using the <Field /> component, which gives you complete flexibility over the markup and styling.
- Uses React Hook Form's
useFormhook for form state management. <Controller />component for controlled inputs.<Field />components for building accessible forms.- Client-side validation using Zod with
zodResolver.
Anatomy
Here's a basic example of a form using the <Controller /> component from React Hook Form and the <Field /> component.
<Controller
name="title"
control={form.control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel htmlFor={field.name}>Bug Title</FieldLabel>
<Input
{...field}
id={field.name}
aria-invalid={fieldState.invalid}
placeholder="Login button not working on mobile"
autoComplete="off"
/>
<FieldDescription>
Provide a concise title for your bug report.
</FieldDescription>
{fieldState.invalid && <FieldError errors={[fieldState.error]} />}
</Field>
)}
/>Form
Create a form schema
We'll start by defining the shape of our form using a Zod schema.
import * as z from "zod"
const formSchema = z.object({
title: z
.string()
.min(5, "Bug title must be at least 5 characters.")
.max(32, "Bug title must be at most 32 characters."),
description: z
.string()
.min(20, "Description must be at least 20 characters.")
.max(100, "Description must be at most 100 characters."),
})Set up the form
Next, we'll use the useForm hook from React Hook Form to create our form instance. We'll also add the Zod resolver to validate the form data.
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import * as z from "zod"
const formSchema = z.object({
title: z
.string()
.min(5, "Bug title must be at least 5 characters.")
.max(32, "Bug title must be at most 32 characters."),
description: z
.string()
.min(20, "Description must be at least 20 characters.")
.max(100, "Description must be at most 100 characters."),
})
export function BugReportForm() {
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
title: "",
description: "",
},
})
function onSubmit(data: z.infer<typeof formSchema>) {
// Do something with the form values.
console.log(data)
}
return (
<form onSubmit={form.handleSubmit(onSubmit)}>
{/* ... */}
{/* Build the form here */}
{/* ... */}
</form>
)
}Build the form
We can now build the form using the <Controller /> component from React Hook Form and the <Field /> component.
Done
That's it. You now have a fully accessible form with client-side validation.
When you submit the form, the onSubmit function will be called with the validated form data. If the form data is invalid, React Hook Form will display the errors next to each field.
Validation
Client-side Validation
React Hook Form validates your form data using the Zod schema. Define a schema and pass it to the resolver option of the useForm hook.
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import * as z from "zod"
const formSchema = z.object({
title: z.string(),
description: z.string().optional(),
})
export function ExampleForm() {
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
title: "",
description: "",
},
})
}Validation Modes
React Hook Form supports different validation modes.
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
mode: "onChange",
})| Mode | Description |
|---|---|
"onChange" |
Validation triggers on every change. |
"onBlur" |
Validation triggers on blur. |
"onSubmit" |
Validation triggers on submit (default). |
"onTouched" |
Validation triggers on first blur, then on every change. |
"all" |
Validation triggers on blur and change. |
Displaying Errors
Display errors next to the field using <FieldError />. For styling and accessibility:
- Add the
data-invalidprop to the<Field />component. - Add the
aria-invalidprop to the form control such as ``,<SelectTrigger />,<Checkbox />, etc.
<Controller
name="email"
control={form.control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel htmlFor={field.name}>Email</FieldLabel>
<Input
{...field}
id={field.name}
type="email"
aria-invalid={fieldState.invalid}
/>
{fieldState.invalid && <FieldError errors={[fieldState.error]} />}
</Field>
)}
/>Working with Different Field Types
Input
- For input fields, spread the
fieldobject onto the `` component. - To show errors, add the
aria-invalidprop to the `` component and thedata-invalidprop to the<Field />component.
For simple text inputs, spread the field object onto the input.
<Controller
name="name"
control={form.control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel htmlFor={field.name}>Name</FieldLabel>
<Input {...field} id={field.name} aria-invalid={fieldState.invalid} />
{fieldState.invalid && <FieldError errors={[fieldState.error]} />}
</Field>
)}
/>Textarea
- For textarea fields, spread the
fieldobject onto the<Textarea />component. - To show errors, add the
aria-invalidprop to the<Textarea />component and thedata-invalidprop to the<Field />component.
For textarea fields, spread the field object onto the textarea.
<Controller
name="about"
control={form.control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel htmlFor="form-rhf-textarea-about">More about you</FieldLabel>
<Textarea
{...field}
id="form-rhf-textarea-about"
aria-invalid={fieldState.invalid}
placeholder="I'm a software engineer..."
className="min-h-[120px]"
/>
<FieldDescription>
Tell us more about yourself. This will be used to help us personalize
your experience.
</FieldDescription>
{fieldState.invalid && <FieldError errors={[fieldState.error]} />}
</Field>
)}
/>Select
- For select components, use
field.valueandfield.onChangeon the<Select />component. - To show errors, add the
aria-invalidprop to the<SelectTrigger />component and thedata-invalidprop to the<Field />component.
<Controller
name="language"
control={form.control}
render={({ field, fieldState }) => (
<Field orientation="responsive" data-invalid={fieldState.invalid}>
<FieldContent>
<FieldLabel htmlFor="form-rhf-select-language">
Spoken Language
</FieldLabel>
<FieldDescription>
For best results, select the language you speak.
</FieldDescription>
{fieldState.invalid && <FieldError errors={[fieldState.error]} />}
</FieldContent>
<Select
name={field.name}
value={field.value}
onValueChange={field.onChange}
>
<SelectTrigger
id="form-rhf-select-language"
aria-invalid={fieldState.invalid}
className="min-w-[120px]"
>
<SelectValue placeholder="Select" />
</SelectTrigger>
<SelectContent position="item-aligned">
<SelectItem value="auto">Auto</SelectItem>
<SelectItem value="en">English</SelectItem>
</SelectContent>
</Select>
</Field>
)}
/>Checkbox
- For checkbox arrays, use
field.valueandfield.onChangewith array manipulation. - To show errors, add the
aria-invalidprop to the<Checkbox />component and thedata-invalidprop to the<Field />component. - Remember to add
data-slot="checkbox-group"to the<FieldGroup />component for proper styling and spacing.
<Controller
name="tasks"
control={form.control}
render={({ field, fieldState }) => (
<FieldSet>
<FieldLegend variant="label">Tasks</FieldLegend>
<FieldDescription>
Get notified when tasks you've created have updates.
</FieldDescription>
<FieldGroup data-slot="checkbox-group">
{tasks.map((task) => (
<Field
key={task.id}
orientation="horizontal"
data-invalid={fieldState.invalid}
>
<Checkbox
id={`form-rhf-checkbox-${task.id}`}
name={field.name}
aria-invalid={fieldState.invalid}
checked={field.value.includes(task.id)}
onCheckedChange={(checked) => {
const newValue = checked
? [...field.value, task.id]
: field.value.filter((value) => value !== task.id)
field.onChange(newValue)
}}
/>
<FieldLabel
htmlFor={`form-rhf-checkbox-${task.id}`}
className="font-normal"
>
{task.label}
</FieldLabel>
</Field>
))}
</FieldGroup>
{fieldState.invalid && <FieldError errors={[fieldState.error]} />}
</FieldSet>
)}
/>Radio Group
- For radio groups, use
field.valueandfield.onChangeon the<RadioGroup />component. - To show errors, add the
aria-invalidprop to the<RadioGroupItem />component and thedata-invalidprop to the<Field />component.
<Controller
name="plan"
control={form.control}
render={({ field, fieldState }) => (
<FieldSet>
<FieldLegend>Plan</FieldLegend>
<FieldDescription>
You can upgrade or downgrade your plan at any time.
</FieldDescription>
<RadioGroup
name={field.name}
value={field.value}
onValueChange={field.onChange}
>
{plans.map((plan) => (
<FieldLabel key={plan.id} htmlFor={`form-rhf-radiogroup-${plan.id}`}>
<Field orientation="horizontal" data-invalid={fieldState.invalid}>
<FieldContent>
<FieldTitle>{plan.title}</FieldTitle>
<FieldDescription>{plan.description}</FieldDescription>
</FieldContent>
<RadioGroupItem
value={plan.id}
id={`form-rhf-radiogroup-${plan.id}`}
aria-invalid={fieldState.invalid}
/>
</Field>
</FieldLabel>
))}
</RadioGroup>
{fieldState.invalid && <FieldError errors={[fieldState.error]} />}
</FieldSet>
)}
/>Switch
- For switches, use
field.valueandfield.onChangeon the<Switch />component. - To show errors, add the
aria-invalidprop to the<Switch />component and thedata-invalidprop to the<Field />component.
<Controller
name="twoFactor"
control={form.control}
render={({ field, fieldState }) => (
<Field orientation="horizontal" data-invalid={fieldState.invalid}>
<FieldContent>
<FieldLabel htmlFor="form-rhf-switch-twoFactor">
Multi-factor authentication
</FieldLabel>
<FieldDescription>
Enable multi-factor authentication to secure your account.
</FieldDescription>
{fieldState.invalid && <FieldError errors={[fieldState.error]} />}
</FieldContent>
<Switch
id="form-rhf-switch-twoFactor"
name={field.name}
checked={field.value}
onCheckedChange={field.onChange}
aria-invalid={fieldState.invalid}
/>
</Field>
)}
/>Complex Forms
Here is an example of a more complex form with multiple fields and validation.
Resetting the Form
Use form.reset() to reset the form to its default values.
<Button type="button" variant="outline" onClick={() => form.reset()}>
Reset
</Button>Array Fields
React Hook Form provides a useFieldArray hook for managing dynamic array fields. This is useful when you need to add or remove fields dynamically.
Using useFieldArray
Use the useFieldArray hook to manage array fields. It provides fields, append, and remove methods.
import { useFieldArray, useForm } from "react-hook-form"
export function ExampleForm() {
const form = useForm({
// ... form config
})
const { fields, append, remove } = useFieldArray({
control: form.control,
name: "emails",
})
}Array Field Structure
Wrap your array fields in a <FieldSet /> with a <FieldLegend /> and <FieldDescription />.
<FieldSet className="gap-4">
<FieldLegend variant="label">Email Addresses</FieldLegend>
<FieldDescription>
Add up to 5 email addresses where we can contact you.
</FieldDescription>
<FieldGroup className="gap-4">{/* Array items go here */}</FieldGroup>
</FieldSet>Controller Pattern for Array Items
Map over the fields array and use <Controller /> for each item. Make sure to use field.id as the key.
{
fields.map((field, index) => (
<Controller
key={field.id}
name={`emails.${index}.address`}
control={form.control}
render={({ field: controllerField, fieldState }) => (
<Field orientation="horizontal" data-invalid={fieldState.invalid}>
<FieldContent>
<InputGroup>
<InputGroupInput
{...controllerField}
id={`form-rhf-array-email-${index}`}
aria-invalid={fieldState.invalid}
placeholder="[email protected]"
type="email"
autoComplete="email"
/>
{/* Remove button */}
</InputGroup>
{fieldState.invalid && <FieldError errors={[fieldState.error]} />}
</FieldContent>
</Field>
)}
/>
))
}Adding Items
Use the append method to add new items to the array.
<Button
type="button"
variant="outline"
size="sm"
onClick={() => append({ address: "" })}
disabled={fields.length >= 5}
>
Add Email Address
</Button>Removing Items
Use the remove method to remove items from the array. Add the remove button conditionally.
{
fields.length > 1 && (
<InputGroupAddon align="inline-end">
<InputGroupButton
type="button"
variant="ghost"
size="icon-xs"
onClick={() => remove(index)}
aria-label={`Remove email ${index + 1}`}
>
<XIcon />
</InputGroupButton>
</InputGroupAddon>
)
}Array Validation
Use Zod's array method to validate array fields.
const formSchema = z.object({
emails: z
.array(
z.object({
address: z.string().email("Enter a valid email address."),
})
)
.min(1, "Add at least one email address.")
.max(5, "You can add up to 5 email addresses."),
})Apps V4 Content Docs Forms Tanstack Form (`apps/v4/content/docs/forms/tanstack-form.mdx`)
title: TanStack Form links: doc: https://tanstack.com/form
import { InfoIcon } from "lucide-react"
This guide explores how to build forms using TanStack Form. You'll learn to create forms with the <Field /> component, implement schema validation with Zod, handle errors, and ensure accessibility.
Demo
We'll start by building the following form. It has a simple text input and a textarea. On submit, we'll validate the form data and display any errors.
Approach
This form leverages TanStack Form for powerful, headless form handling. We'll build our form using the <Field /> component, which gives you complete flexibility over the markup and styling.
- Uses TanStack Form's
useFormhook for form state management. form.Fieldcomponent with render prop pattern for controlled inputs.<Field />components for building accessible forms.- Client-side validation using Zod.
- Real-time validation feedback.
Anatomy
Here's a basic example of a form using TanStack Form with the <Field /> component.
<form
onSubmit={(e) => {
e.preventDefault()
form.handleSubmit()
}}
>
<FieldGroup>
<form.Field
name="title"
children={(field) => {
const isInvalid =
field.state.meta.isTouched && !field.state.meta.isValid
return (
<Field data-invalid={isInvalid}>
<FieldLabel htmlFor={field.name}>Bug Title</FieldLabel>
<Input
id={field.name}
name={field.name}
value={field.state.value}
onBlur={field.handleBlur}
onChange={(e) => field.handleChange(e.target.value)}
aria-invalid={isInvalid}
placeholder="Login button not working on mobile"
autoComplete="off"
/>
<FieldDescription>
Provide a concise title for your bug report.
</FieldDescription>
{isInvalid && <FieldError errors={field.state.meta.errors} />}
</Field>
)
}}
/>
</FieldGroup>
<Button type="submit">Submit</Button>
</form>Form
Create a schema
We'll start by defining the shape of our form using a Zod schema.
import * as z from "zod"
const formSchema = z.object({
title: z
.string()
.min(5, "Bug title must be at least 5 characters.")
.max(32, "Bug title must be at most 32 characters."),
description: z
.string()
.min(20, "Description must be at least 20 characters.")
.max(100, "Description must be at most 100 characters."),
})Set up the form
Use the useForm hook from TanStack Form to create your form instance with Zod validation.
import { useForm } from "@tanstack/react-form"
import { toast } from "sonner"
import * as z from "zod"
const formSchema = z.object({
// ...
})
export function BugReportForm() {
const form = useForm({
defaultValues: {
title: "",
description: "",
},
validators: {
onSubmit: formSchema,
},
onSubmit: async ({ value }) => {
toast.success("Form submitted successfully")
},
})
return (
<form
onSubmit={(e) => {
e.preventDefault()
form.handleSubmit()
}}
>
{/* ... */}
</form>
)
}We are using onSubmit to validate the form data here. TanStack Form supports other validation modes, which you can read about in the documentation.
Build the form
We can now build the form using the form.Field component from TanStack Form and the <Field /> component.
Done
That's it. You now have a fully accessible form with client-side validation.
When you submit the form, the onSubmit function will be called with the validated form data. If the form data is invalid, TanStack Form will display the errors next to each field.
Validation
Client-side Validation
TanStack Form validates your form data using the Zod schema. Validation happens in real-time as the user types.
import { useForm } from "@tanstack/react-form"
const formSchema = z.object({
// ...
})
export function BugReportForm() {
const form = useForm({
defaultValues: {
title: "",
description: "",
},
validators: {
onSubmit: formSchema,
},
onSubmit: async ({ value }) => {
console.log(value)
},
})
return <form onSubmit={/* ... */}>{/* ... */}</form>
}Validation Modes
TanStack Form supports different validation strategies through the validators option:
| Mode | Description |
|---|---|
"onChange" |
Validation triggers on every change. |
"onBlur" |
Validation triggers on blur. |
"onSubmit" |
Validation triggers on submit. |
const form = useForm({
defaultValues: {
title: "",
description: "",
},
validators: {
onSubmit: formSchema,
onChange: formSchema,
onBlur: formSchema,
},
})Displaying Errors
Display errors next to the field using <FieldError />. For styling and accessibility:
- Add the
data-invalidprop to the<Field />component. - Add the
aria-invalidprop to the form control such as ``,<SelectTrigger />,<Checkbox />, etc.
<form.Field
name="email"
children={(field) => {
const isInvalid = field.state.meta.isTouched && !field.state.meta.isValid
return (
<Field data-invalid={isInvalid}>
<FieldLabel htmlFor={field.name}>Email</FieldLabel>
<Input
id={field.name}
name={field.name}
value={field.state.value}
onBlur={field.handleBlur}
onChange={(e) => field.handleChange(e.target.value)}
type="email"
aria-invalid={isInvalid}
/>
{isInvalid && <FieldError errors={field.state.meta.errors} />}
</Field>
)
}}
/>Working with Different Field Types
Input
- For input fields, use
field.state.valueandfield.handleChangeon the `` component. - To show errors, add the
aria-invalidprop to the `` component and thedata-invalidprop to the<Field />component.
<form.Field
name="username"
children={(field) => {
const isInvalid = field.state.meta.isTouched && !field.state.meta.isValid
return (
<Field data-invalid={isInvalid}>
<FieldLabel htmlFor="form-tanstack-input-username">Username</FieldLabel>
<Input
id="form-tanstack-input-username"
name={field.name}
value={field.state.value}
onBlur={field.handleBlur}
onChange={(e) => field.handleChange(e.target.value)}
aria-invalid={isInvalid}
placeholder="shadcn"
autoComplete="username"
/>
<FieldDescription>
This is your public display name. Must be between 3 and 10 characters.
Must only contain letters, numbers, and underscores.
</FieldDescription>
{isInvalid && <FieldError errors={field.state.meta.errors} />}
</Field>
)
}}
/>Textarea
- For textarea fields, use
field.state.valueandfield.handleChangeon the<Textarea />component. - To show errors, add the
aria-invalidprop to the<Textarea />component and thedata-invalidprop to the<Field />component.
<form.Field
name="about"
children={(field) => {
const isInvalid = field.state.meta.isTouched && !field.state.meta.isValid
return (
<Field data-invalid={isInvalid}>
<FieldLabel htmlFor="form-tanstack-textarea-about">
More about you
</FieldLabel>
<Textarea
id="form-tanstack-textarea-about"
name={field.name}
value={field.state.value}
onBlur={field.handleBlur}
onChange={(e) => field.handleChange(e.target.value)}
aria-invalid={isInvalid}
placeholder="I'm a software engineer..."
className="min-h-[120px]"
/>
<FieldDescription>
Tell us more about yourself. This will be used to help us personalize
your experience.
</FieldDescription>
{isInvalid && <FieldError errors={field.state.meta.errors} />}
</Field>
)
}}
/>Select
- For select components, use
field.state.valueandfield.handleChangeon the<Select />component. - To show errors, add the
aria-invalidprop to the<SelectTrigger />component and thedata-invalidprop to the<Field />component.
<form.Field
name="language"
children={(field) => {
const isInvalid = field.state.meta.isTouched && !field.state.meta.isValid
return (
<Field orientation="responsive" data-invalid={isInvalid}>
<FieldContent>
<FieldLabel htmlFor="form-tanstack-select-language">
Spoken Language
</FieldLabel>
<FieldDescription>
For best results, select the language you speak.
</FieldDescription>
{isInvalid && <FieldError errors={field.state.meta.errors} />}
</FieldContent>
<Select
name={field.name}
value={field.state.value}
onValueChange={field.handleChange}
>
<SelectTrigger
id="form-tanstack-select-language"
aria-invalid={isInvalid}
className="min-w-[120px]"
>
<SelectValue placeholder="Select" />
</SelectTrigger>
<SelectContent position="item-aligned">
<SelectItem value="auto">Auto</SelectItem>
<SelectItem value="en">English</SelectItem>
</SelectContent>
</Select>
</Field>
)
}}
/>Checkbox
- For checkbox, use
field.state.valueandfield.handleChangeon the<Checkbox />component. - To show errors, add the
aria-invalidprop to the<Checkbox />component and thedata-invalidprop to the<Field />component. - For checkbox arrays, use
mode="array"on the<form.Field />component and TanStack Form's array helpers. - Remember to add
data-slot="checkbox-group"to the<FieldGroup />component for proper styling and spacing.
/* Detailed source-code truncated for AI context efficiency. */Radio Group
- For radio groups, use
field.state.valueandfield.handleChangeon the<RadioGroup />component. - To show errors, add the
aria-invalidprop to the<RadioGroupItem />component and thedata-invalidprop to the<Field />component.
<form.Field
name="plan"
children={(field) => {
const isInvalid = field.state.meta.isTouched && !field.state.meta.isValid
return (
<FieldSet>
<FieldLegend>Plan</FieldLegend>
<FieldDescription>
You can upgrade or downgrade your plan at any time.
</FieldDescription>
<RadioGroup
name={field.name}
value={field.state.value}
onValueChange={field.handleChange}
>
{plans.map((plan) => (
<FieldLabel
key={plan.id}
htmlFor={`form-tanstack-radiogroup-${plan.id}`}
>
<Field orientation="horizontal" data-invalid={isInvalid}>
<FieldContent>
<FieldTitle>{plan.title}</FieldTitle>
<FieldDescription>{plan.description}</FieldDescription>
</FieldContent>
<RadioGroupItem
value={plan.id}
id={`form-tanstack-radiogroup-${plan.id}`}
aria-invalid={isInvalid}
/>
</Field>
</FieldLabel>
))}
</RadioGroup>
{isInvalid && <FieldError errors={field.state.meta.errors} />}
</FieldSet>
)
}}
/>Switch
- For switches, use
field.state.valueandfield.handleChangeon the<Switch />component. - To show errors, add the
aria-invalidprop to the<Switch />component and thedata-invalidprop to the<Field />component.
<form.Field
name="twoFactor"
children={(field) => {
const isInvalid = field.state.meta.isTouched && !field.state.meta.isValid
return (
<Field orientation="horizontal" data-invalid={isInvalid}>
<FieldContent>
<FieldLabel htmlFor="form-tanstack-switch-twoFactor">
Multi-factor authentication
</FieldLabel>
<FieldDescription>
Enable multi-factor authentication to secure your account.
</FieldDescription>
{isInvalid && <FieldError errors={field.state.meta.errors} />}
</FieldContent>
<Switch
id="form-tanstack-switch-twoFactor"
name={field.name}
checked={field.state.value}
onCheckedChange={field.handleChange}
aria-invalid={isInvalid}
/>
</Field>
)
}}
/>Complex Forms
Here is an example of a more complex form with multiple fields and validation.
Resetting the Form
Use form.reset() to reset the form to its default values.
<Button type="button" variant="outline" onClick={() => form.reset()}>
Reset
</Button>Array Fields
TanStack Form provides powerful array field management with mode="array". This allows you to dynamically add, remove, and update array items with full validation support.
This example demonstrates managing multiple email addresses with array fields. Users can add up to 5 email addresses, remove individual addresses, and each address is validated independently.
Array Field Structure
Use mode="array" on the parent field to enable array field management.
<form.Field
name="emails"
mode="array"
children={(field) => {
return (
<FieldSet>
<FieldLegend variant="label">Email Addresses</FieldLegend>
<FieldDescription>
Add up to 5 email addresses where we can contact you.
</FieldDescription>
<FieldGroup>
{field.state.value.map((_, index) => (
// Nested field for each array item
))}
</FieldGroup>
</FieldSet>
)
}}
/>Nested Fields
Access individual array items using bracket notation: fieldName[index].propertyName. This example uses InputGroup to display the remove button inline with the input.
<form.Field
name={`emails[${index}].address`}
children={(subField) => {
const isSubFieldInvalid =
subField.state.meta.isTouched && !subField.state.meta.isValid
return (
<Field orientation="horizontal" data-invalid={isSubFieldInvalid}>
<FieldContent>
<InputGroup>
<InputGroupInput
id={`form-tanstack-array-email-${index}`}
name={subField.name}
value={subField.state.value}
onBlur={subField.handleBlur}
onChange={(e) => subField.handleChange(e.target.value)}
aria-invalid={isSubFieldInvalid}
placeholder="[email protected]"
type="email"
/>
{field.state.value.length > 1 && (
<InputGroupAddon align="inline-end">
<InputGroupButton
type="button"
variant="ghost"
size="icon-xs"
onClick={() => field.removeValue(index)}
aria-label={`Remove email ${index + 1}`}
>
<XIcon />
</InputGroupButton>
</InputGroupAddon>
)}
</InputGroup>
{isSubFieldInvalid && (
<FieldError errors={subField.state.meta.errors} />
)}
</FieldContent>
</Field>
)
}}
/>Adding Items
Use field.pushValue(item) to add items to an array field. You can disable the button when the array reaches its maximum length.
<Button
type="button"
variant="outline"
size="sm"
onClick={() => field.pushValue({ address: "" })}
disabled={field.state.value.length >= 5}
>
Add Email Address
</Button>Removing Items
Use field.removeValue(index) to remove items from an array field. You can conditionally show the remove button only when there's more than one item.
{
field.state.value.length > 1 && (
<InputGroupButton
onClick={() => field.removeValue(index)}
aria-label={`Remove email ${index + 1}`}
>
<XIcon />
</InputGroupButton>
)
}Array Validation
Validate array fields using Zod's array methods.
const formSchema = z.object({
emails: z
.array(
z.object({
address: z.string().email("Enter a valid email address."),
})
)
.min(1, "Add at least one email address.")
.max(5, "You can add up to 5 email addresses."),
})Apps V4 Content Docs Installation Astro (`apps/v4/content/docs/installation/astro.mdx`)
title: Astro
Choose the setup that matches your starting point.
<LinkedCard
href="#scaffold-with-create"
className="items-start gap-1 p-6 text-sm md:p-6"
Use shadcn/create
Build your preset and generate an Astro project command.Scaffold a new Astro project directly from the terminal.Configure shadcn/ui manually in an existing Astro project.Use shadcn/create
Build Your Preset
Open shadcn/create and build your preset visually. Choose your style, colors, fonts, icons, and more.
Open shadcn/createCreate Project
Click Create Project, choose your package manager, and copy the generated command.
The generated command will look similar to this:
npx shadcn@latest init --preset [CODE] --template astroThe exact command will include your selected options such as --base, --monorepo, or --rtl.
Add Components
Add the Card component to your project:
npx shadcn@latest add cardIf you created a monorepo, run the command from apps/web or specify the workspace from the repo root:
npx shadcn@latest add card -c apps/webThe command above will add the Card component to your project. You can then import it like this:
---
import Layout from "@/layouts/main.astro"
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card"
---
<Layout>
<Card className="max-w-sm">
<CardHeader>
<CardTitle>Project Overview</CardTitle>
<CardDescription>
Track progress and recent activity for your Astro app.
</CardDescription>
</CardHeader>
<CardContent>
Your design system is ready. Start building your next component.
</CardContent>
</Card>
</Layout>If you created a monorepo, update apps/web/src/pages/index.astro and import from @workspace/ui/components/card instead. The monorepo layout at apps/web/src/layouts/main.astro already imports @workspace/ui/globals.css for you.
Use the CLI
Create Project
Run the init command to scaffold a new Astro project. Follow the prompts to configure your project: base, preset, monorepo, and more.
npx shadcn@latest init -t astroFor a monorepo project, use --monorepo flag:
npx shadcn@latest init -t astro --monorepoAdd Components
Add the Card component to your project:
npx shadcn@latest add cardIf you created a monorepo, run the command from apps/web or specify the workspace from the repo root:
npx shadcn@latest add card -c apps/webThe command above will add the Card component to your project. You can then import it like this:
---
import Layout from "@/layouts/main.astro"
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card"
---
<Layout>
<Card className="max-w-sm">
<CardHeader>
<CardTitle>Project Overview</CardTitle>
<CardDescription>
Track progress and recent activity for your Astro app.
</CardDescription>
</CardHeader>
<CardContent>
Your design system is ready. Start building your next component.
</CardContent>
</Card>
</Layout>If you created a monorepo, update apps/web/src/pages/index.astro and import from @workspace/ui/components/card instead. The monorepo layout at apps/web/src/layouts/main.astro already imports @workspace/ui/globals.css for you.
Existing Project
Create Project
If you need a new Astro project, create one first. Otherwise, skip this step.
npm create astro@latest astro-app -- --template with-tailwindcss --install --add react --gitThis command sets up Tailwind CSS and the React integration for you. If you're adding shadcn/ui to an older or custom Astro app, make sure both are configured before continuing.
The Tailwind starter loads your global stylesheet through src/layouts/main.astro. Keep that layout in place, or make sure your page imports @/styles/global.css.
Edit tsconfig.json file
If your project already has the @/* alias configured, skip this step.
Add the following code to the tsconfig.json file to resolve paths:
{
"compilerOptions": {
// ...
"baseUrl": ".",
"paths": {
"@/*": [
"./src/*"
]
}
// ...
}
}Run the CLI
Run the shadcn init command to set up your project:
npx shadcn@latest initAdd Components
You can now start adding components to your project.
npx shadcn@latest add buttonThe command above will add the Button component to your project. You can then import it like this:
---
import Layout from "@/layouts/main.astro"
import { Button } from "@/components/ui/button"
---
<Layout>
<div class="grid h-screen place-items-center content-center">
<Button>Button</Button>
</div>
</Layout>Apps V4 Content Docs Installation Gatsby (`apps/v4/content/docs/installation/gatsby.mdx`)
title: Gatsby
Create project
Start by creating a new Gatsby project using create-gatsby:
npm init gatsbyConfigure your Gatsby project to use TypeScript and Tailwind CSS
You will be asked a few questions to configure your project:
✔ What would you like to call your site?
· your-app-name
✔ What would you like to name the folder where your site will be created?
· your-app-name
✔ Will you be using JavaScript or TypeScript?
· TypeScript
✔ Will you be using a CMS?
· Choose whatever you want
✔ Would you like to install a styling system?
· Tailwind CSS
✔ Would you like to install additional features with other plugins?
· Choose whatever you want
✔ Shall we do this? (Y/n) · YesEdit tsconfig.json file
Add the following code to the tsconfig.json file to resolve paths:
{
"compilerOptions": {
// ...
"baseUrl": ".",
"paths": {
"@/*": [
"./src/*"
]
}
// ...
}
}Create gatsby-node.ts file
Create a gatsby-node.ts file at the root of your project if it doesn’t already exist, and add the code below to the gatsby-node file so your app can resolve paths:
import * as path from "path"
export const onCreateWebpackConfig = ({ actions }) => {
actions.setWebpackConfig({
resolve: {
alias: {
"@/components": path.resolve(__dirname, "src/components"),
"@/lib/utils": path.resolve(__dirname, "src/lib/utils"),
},
},
})
}Run the CLI
Run the shadcn init command to set up your project:
npx shadcn@latest initThat's it
You can now start adding components to your project.
npx shadcn@latest add buttonThe command above will add the Button component to your project. You can then import it like this:
import { Button } from "@/components/ui/button"
export default function Home() {
return (
<div>
<Button>Click me</Button>
</div>
)
}Apps V4 Content Docs Installation Laravel (`apps/v4/content/docs/installation/laravel.mdx`)
title: Laravel
The shadcn CLI does not scaffold a new Laravel app. Start by creating a Laravel app with the React starter kit, then choose how you want to configure shadcn/ui.
Create Project
Create a new Laravel app using the Laravel installer:
laravel new my-appIf you already have a Laravel app with React and Inertia configured, skip this step.
Choose the React starter kit when prompted. For more information, see the official Laravel frontend documentation.
Then move into your project directory:
cd my-app <LinkedCard
href="#configure-with-create"
className="items-start gap-1 p-6 text-sm md:p-6"
Use shadcn/create
Build your preset visually and generate a Laravel init command.Configure shadcn/ui in your Laravel app directly from the terminal.Use shadcn/create
Build Your Preset
Open shadcn/create and build your preset visually. Choose your style, colors, fonts, icons, and more.
Open shadcn/createRun the Command
Click Create Project, choose your package manager, and copy the generated command.
The generated command will look similar to this:
npx shadcn@latest init --preset [CODE] --template laravelRun the command from the root of your Laravel app.
When asked to overwrite components.json and components, choose Yes.
Add Components
Add the Switch component to your project:
npx shadcn@latest add switchThe command above will add the Switch component to resources/js/components/ui/switch.tsx. You can then import it like this:
import { Switch } from "@/components/ui/switch"
const MyPage = () => {
return (
<div>
<Switch />
</div>
)
}
export default MyPageUse the CLI
Run the CLI
Run the shadcn init command from the root of your Laravel app:
npx shadcn@latest initWhen asked to overwrite components.json and components, choose Yes.
Add Components
Add the Switch component to your project:
npx shadcn@latest add switchThe command above will add the Switch component to resources/js/components/ui/switch.tsx. You can then import it like this:
import { Switch } from "@/components/ui/switch"
const MyPage = () => {
return (
<div>
<Switch />
</div>
)
}
export default MyPageApps V4 Content Docs Installation Manual (`apps/v4/content/docs/installation/manual.mdx`)
title: Manual Installation
Add Tailwind CSS
Components are styled using Tailwind CSS. You need to install Tailwind CSS in your project.
Follow the Tailwind CSS installation instructions to get started.
Add dependencies
Add the following dependencies to your project:
npm install shadcn class-variance-authority clsx tailwind-merge lucide-react tw-animate-cssConfigure path aliases
Configure the path aliases in your tsconfig.json file.
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./*"]
}
}
}The @ alias is a preference. You can use other aliases if you want.
Configure styles
Add the following to your styles/globals.css file. You can learn more about using CSS variables for theming in the theming section.
/* Detailed source-code truncated for AI context efficiency. */Add a cn helper
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}Create a `components.json` file
Create a components.json file in the root of your project.
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "radix-nova",
"rsc": false,
"tsx": true,
"tailwind": {
"config": "",
"css": "src/styles/globals.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"iconLibrary": "lucide"
}That's it
You can now start adding components to your project.
Apps V4 Content Docs Installation Meta.Json (`apps/v4/content/docs/installation/meta.json`)
{
"pages": [
"next",
"vite",
"laravel",
"react-router",
"remix",
"astro",
"tanstack",
"tanstack-router",
"manual"
]
}
Apps V4 Content Docs Installation Next (`apps/v4/content/docs/installation/next.mdx`)
title: Next.js
Choose the setup that matches your starting point.
<LinkedCard
href="#scaffold-with-create"
className="items-start gap-1 p-6 text-sm md:p-6"
Use shadcn/create
Build your preset and generate a Next.js project command.Scaffold a new Next.js project directly from the terminal.Configure shadcn/ui manually in an existing Next.js project.Use shadcn/create
Build Your Preset
Open shadcn/create and build your preset visually. Choose your style, colors, fonts, icons, and more.
Open shadcn/createCreate Project
Click Create Project, choose your package manager, and copy the generated command.
The generated command will look similar to this:
npx shadcn@latest init --preset [CODE] --template nextThe exact command will include your selected options such as --base, --monorepo, or --rtl.
Add Components
Add the Card component to your project:
npx shadcn@latest add cardIf you created a monorepo, run the command from apps/web or specify the workspace from the repo root:
npx shadcn@latest add card -c apps/webThe command above will add the Card component to your project. You can then import it like this:
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card"
export default function Home() {
return (
<Card className="max-w-sm">
<CardHeader>
<CardTitle>Project Overview</CardTitle>
<CardDescription>
Track progress and recent activity for your Next.js app.
</CardDescription>
</CardHeader>
<CardContent>
Your design system is ready. Start building your next component.
</CardContent>
</Card>
)
}If you created a monorepo, update apps/web/app/page.tsx and import from @workspace/ui/components/card instead.
Use the CLI
Create Project
Run the init command to scaffold a new Next.js project. Follow the prompts to configure your project: base, preset, monorepo, and more.
npx shadcn@latest init -t nextFor a monorepo project, use --monorepo flag:
npx shadcn@latest init -t next --monorepoAdd Components
Add the Card component to your project:
npx shadcn@latest add cardIf you created a monorepo, run the command from apps/web or specify the workspace from the repo root:
npx shadcn@latest add card -c apps/webThe command above will add the Card component to your project. You can then import it like this:
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card"
export default function Home() {
return (
<Card className="max-w-sm">
<CardHeader>
<CardTitle>Project Overview</CardTitle>
<CardDescription>
Track progress and recent activity for your Next.js app.
</CardDescription>
</CardHeader>
<CardContent>
Your design system is ready. Start building your next component.
</CardContent>
</Card>
)
}If you created a monorepo, update apps/web/app/page.tsx and import from @workspace/ui/components/card instead.
Existing Project
Create Project
If you need a new Next.js project, create one with create-next-app. Otherwise, skip this step.
npx create-next-app@latestChoose the recommended defaults so Tailwind CSS, the App Router, and the default @/* import alias are configured for you.
If you prefer a src/ directory, use --src-dir or choose Yes when prompted:
npx create-next-app@latest --src-dirWith --src-dir, Next.js places your app in src/app and configures the @/* alias to point to ./src/*.
Configure Tailwind CSS and Import Aliases
If you created your project with the recommended create-next-app defaults, you can skip this step.
If you're adding shadcn/ui to an older or custom Next.js app, make sure Tailwind CSS is installed first. You can follow the official Next.js installation guide.
Then make sure your tsconfig.json includes the @/* import alias:
{
"compilerOptions": {
"paths": {
"@/*": ["./*"]
}
}
}If you used --src-dir, point the alias to ./src/* instead.
Run the CLI
Run the shadcn init command to set up shadcn/ui in your project.
npx shadcn@latest initAdd Components
You can now start adding components to your project.
npx shadcn@latest add buttonThe command above will add the Button component to your project. You can then import it like this:
import { Button } from "@/components/ui/button"
export default function Home() {
return (
<div className="flex min-h-svh items-center justify-center">
<Button>Click me</Button>
</div>
)
}If you used --src-dir, add the component to src/app/page.tsx instead.
Apps V4 Content Docs Installation React Router (`apps/v4/content/docs/installation/react-router.mdx`)
title: React Router
Choose the setup that matches your starting point.
<LinkedCard
href="#scaffold-with-create"
className="items-start gap-1 p-6 text-sm md:p-6"
Use shadcn/create
Build your preset and generate a React Router project.Scaffold a new React Router project directly from the terminal.Configure shadcn/ui manually in an existing React Router project.Use shadcn/create
Build Your Preset
Open shadcn/create and build your preset visually. Choose your style, colors, fonts, icons, and more.
Open shadcn/createCreate Project
Click Create Project, choose your package manager, and copy the generated command.
The generated command will look similar to this:
npx shadcn@latest init --preset [CODE] --template react-routerThe exact command will include your selected options such as --base, --monorepo, or --rtl.
Add Components
Add the Card component to your project:
npx shadcn@latest add cardIf you created a monorepo, run the command from apps/web or specify the workspace from the repo root:
npx shadcn@latest add card -c apps/webThe command above will add the Card component to your project. You can then import it like this:
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "~/components/ui/card"
export default function Home() {
return (
<Card className="max-w-sm">
<CardHeader>
<CardTitle>Project Overview</CardTitle>
<CardDescription>
Track progress and recent activity for your React Router app.
</CardDescription>
</CardHeader>
<CardContent>
Your design system is ready. Start building your next component.
</CardContent>
</Card>
)
}If you created a monorepo, update apps/web/app/routes/home.tsx and import from @workspace/ui/components/card instead.
Use the CLI
Create Project
Run the init command to scaffold a new React Router project. Follow the prompts to configure your project: base, preset, monorepo, and more.
npx shadcn@latest init -t react-routerFor a monorepo project, use --monorepo flag:
npx shadcn@latest init -t react-router --monorepoAdd Components
Add the Card component to your project:
npx shadcn@latest add cardIf you created a monorepo, run the command from apps/web or specify the workspace from the repo root:
npx shadcn@latest add card -c apps/webThe command above will add the Card component to your project. You can then import it like this:
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "~/components/ui/card"
export default function Home() {
return (
<Card className="max-w-sm">
<CardHeader>
<CardTitle>Project Overview</CardTitle>
<CardDescription>
Track progress and recent activity for your React Router app.
</CardDescription>
</CardHeader>
<CardContent>
Your design system is ready. Start building your next component.
</CardContent>
</Card>
)
}If you created a monorepo, update apps/web/app/routes/home.tsx and import from @workspace/ui/components/card instead.
Existing Project
Create Project
If you need a new React Router project, create one first. Otherwise, skip this step.
npm create react-router@latestcreate-react-router already configures Tailwind CSS and the default ~/* import alias for you. If you're adding shadcn/ui to an older or custom React Router app, make sure both are configured before continuing.
Run the CLI
Run the shadcn init command to set up shadcn/ui in your project.
npx shadcn@latest initAdd Components
You can now start adding components to your project.
npx shadcn@latest add buttonThe command above will add the Button component to your project. You can then import it like this:
import { Button } from "~/components/ui/button"
export default function Home() {
return (
<div className="flex min-h-svh flex-col items-center justify-center">
<Button>Click me</Button>
</div>
)
}Apps V4 Content Docs Installation Remix (`apps/v4/content/docs/installation/remix.mdx`)
title: Remix
Note: This guide is for Remix. For React Router, see the React Router guide.
Create project
Start by creating a new Remix project using create-remix:
npx create-remix@latest my-appRun the CLI
Run the shadcn init command to set up your project:
npx shadcn@latest initThat's it
You can now start adding components to your project.
npx shadcn@latest add buttonThe command above will add the Button component to your project. You can then import it like this:
import { Button } from "~/components/ui/button"
export default function Home() {
return (
<div>
<Button>Click me</Button>
</div>
)
}Apps V4 Content Docs Installation Tanstack Router (`apps/v4/content/docs/installation/tanstack-router.mdx`)
title: TanStack Router
Create project
Start by creating a new TanStack Router project:
npx create-tsrouter-app@latest my-app --template file-router --tailwind --add-ons shadcnAdd Components
You can now start adding components to your project.
npx shadcn@latest add buttonThe command above will add the Button component to your project. You can then import it like this:
import { createFileRoute } from "@tanstack/react-router"
import { Button } from "@/components/ui/button"
export const Route = createFileRoute("/")({
component: App,
})
function App() {
return (
<div>
<Button>Click me</Button>
</div>
)
}Apps V4 Content Docs Installation Tanstack (`apps/v4/content/docs/installation/tanstack.mdx`)
title: TanStack Start
Choose the setup that matches your starting point.
<LinkedCard
href="#scaffold-with-create"
className="items-start gap-1 p-6 text-sm md:p-6"
Use shadcn/create
Build your preset and generate a TanStack project command.Scaffold a new TanStack project from the terminal.Configure shadcn/ui manually in an existing TanStack project.Use shadcn/create
Build Your Preset
Open shadcn/create and build your preset visually. Choose your style, colors, fonts, icons, and more.
Open shadcn/createCreate Project
Click Create Project, choose your package manager, and copy the generated command.
The generated command will look similar to this:
npx shadcn@latest init --preset [CODE] --template startThe exact command will include your selected options such as --base, --monorepo, or --rtl.
Add Components
Add the Card component to your project:
npx shadcn@latest add cardIf you created a monorepo, run the command from apps/web or specify the workspace from the repo root:
npx shadcn@latest add card -c apps/webThe command above will add the Card component to your project. You can then import it like this:
import { createFileRoute } from "@tanstack/react-router"
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card"
export const Route = createFileRoute("/")({
component: App,
})
function App() {
return (
<Card className="max-w-sm">
<CardHeader>
<CardTitle>Project Overview</CardTitle>
<CardDescription>
Track progress and recent activity for your TanStack Start app.
</CardDescription>
</CardHeader>
<CardContent>
Your design system is ready. Start building your next component.
</CardContent>
</Card>
)
}If you created a monorepo, update apps/web/src/routes/index.tsx and import from @workspace/ui/components/card instead.
Use the CLI
Create Project
Run the init command to scaffold a new TanStack Start project. Follow the prompts to configure your project: base, preset, monorepo, and more.
npx shadcn@latest init -t startFor a monorepo project, use --monorepo flag:
npx shadcn@latest init -t start --monorepoAdd Components
Add the Card component to your project:
npx shadcn@latest add cardIf you created a monorepo, run the command from apps/web or specify the workspace from the repo root:
npx shadcn@latest add card -c apps/webThe command above will add the Card component to your project. You can then import it like this:
import { createFileRoute } from "@tanstack/react-router"
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card"
export const Route = createFileRoute("/")({
component: App,
})
function App() {
return (
<Card className="max-w-sm">
<CardHeader>
<CardTitle>Project Overview</CardTitle>
<CardDescription>
Track progress and recent activity for your TanStack Start app.
</CardDescription>
</CardHeader>
<CardContent>
Your design system is ready. Start building your next component.
</CardContent>
</Card>
)
}If you created a monorepo, update apps/web/src/routes/index.tsx and import from @workspace/ui/components/card instead.
Existing Project
Create Project
If you need a new TanStack Start project, create one first. Otherwise, skip this step.
npx @tanstack/cli@latest createChoose TanStack Start, the React framework, and the recommended defaults so Tailwind CSS and the @/* import alias are configured for you.
Do not add the shadcn add-on when prompted. The shadcn CLI will configure shadcn/ui later in this guide.
The TanStack CLI already configures Tailwind CSS and the default @/* import alias for you. If you're adding shadcn/ui to an older or custom TanStack Start app, make sure both are configured before continuing.
Run the CLI
Run the shadcn init command to set up shadcn/ui in your project.
npx shadcn@latest initAdd Components
You can now start adding components to your project.
npx shadcn@latest add buttonThe command above will add the Button component to your project. You can then import it like this:
import { createFileRoute } from "@tanstack/react-router"
import { Button } from "@/components/ui/button"
export const Route = createFileRoute("/")({
component: App,
})
function App() {
return (
<div className="flex min-h-svh items-center justify-center p-6">
<Button>Click me</Button>
</div>
)
}Apps V4 Content Docs Installation Vite (`apps/v4/content/docs/installation/vite.mdx`)
title: Vite
Choose the setup that matches your starting point.
<LinkedCard
href="#scaffold-with-create"
className="items-start gap-1 p-6 text-sm md:p-6"
Use shadcn/create
Build your preset and generate a Vite project command.Scaffold a new Vite project directly from the terminal.Configure shadcn/ui manually in an existing Vite project.Use shadcn/create
Build Your Preset
Open shadcn/create and build your preset visually. Choose your style, colors, fonts, icons, and more.
Open shadcn/createCreate Project
Click Create Project, choose your package manager, and copy the generated command.
The generated command will look similar to this:
npx shadcn@latest init --preset [CODE] --template viteThe exact command will include your selected options such as --base, --monorepo, or --rtl.
Add Components
Add the Card component to your project:
npx shadcn@latest add cardIf you created a monorepo, run the command from apps/web or specify the workspace from the repo root:
npx shadcn@latest add card -c apps/webThe command above will add the Card component to your project. You can then import it like this:
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card"
function App() {
return (
<Card className="max-w-sm">
<CardHeader>
<CardTitle>Project Overview</CardTitle>
<CardDescription>
Track progress and recent activity for your Vite app.
</CardDescription>
</CardHeader>
<CardContent>
Your design system is ready. Start building your next component.
</CardContent>
</Card>
)
}
export default AppIf you created a monorepo, update apps/web/src/App.tsx and import from @workspace/ui/components/card instead.
Use the CLI
Create Project
Run the init command to scaffold a new Vite project. Follow the prompts to configure your project: base, preset, monorepo, and more.
npx shadcn@latest init -t viteFor a monorepo project, use --monorepo flag:
npx shadcn@latest init -t vite --monorepoAdd Components
Add the Card component to your project:
npx shadcn@latest add cardIf you created a monorepo, run the command from apps/web or specify the workspace from the repo root:
npx shadcn@latest add card -c apps/webThe command above will add the Card component to your project. You can then import it like this:
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card"
function App() {
return (
<Card className="max-w-sm">
<CardHeader>
<CardTitle>Project Overview</CardTitle>
<CardDescription>
Track progress and recent activity for your Vite app.
</CardDescription>
</CardHeader>
<CardContent>
Your design system is ready. Start building your next component.
</CardContent>
</Card>
)
}
export default AppIf you created a monorepo, update apps/web/src/App.tsx and import from @workspace/ui/components/card instead.
Existing Project
Create Project
If you need a new Vite project, create one first and select the React + TypeScript template. Otherwise, skip this step.
npm create vite@latestAdd Tailwind CSS
If your project already has Tailwind CSS configured, skip this step.
npm install tailwindcss @tailwindcss/viteReplace everything in src/index.css with the following:
@import "tailwindcss";Edit tsconfig.json file
If your project already has the @/* alias configured, skip this step.
Vite splits TypeScript configuration across multiple files. Add the baseUrl and paths properties to the compilerOptions section of tsconfig.json and tsconfig.app.json:
{
"files": [],
"references": [
{
"path": "./tsconfig.app.json"
},
{
"path": "./tsconfig.node.json"
}
],
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
}
}Edit tsconfig.app.json file
Add the same alias to tsconfig.app.json so your editor can resolve imports:
{
"compilerOptions": {
// ...
"baseUrl": ".",
"paths": {
"@/*": [
"./src/*"
]
}
// ...
}
}Update vite.config.ts
Install @types/node and update vite.config.ts so Vite can resolve the @ alias:
npm install -D @types/nodeimport path from "path"
import tailwindcss from "@tailwindcss/vite"
import react from "@vitejs/plugin-react"
import { defineConfig } from "vite"
// https://vite.dev/config/
export default defineConfig({
plugins: [react(), tailwindcss()],
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
},
})Run the CLI
Run the shadcn init command to set up shadcn/ui in your project:
npx shadcn@latest initAdd Components
You can now start adding components to your project.
npx shadcn@latest add buttonThe command above will add the Button component to your project. You can then import it like this:
import { Button } from "@/components/ui/button"
function App() {
return (
<div className="flex min-h-svh flex-col items-center justify-center">
<Button>Click me</Button>
</div>
)
}
export default AppApps V4 Content Docs Registry Authentication (`apps/v4/content/docs/registry/authentication.mdx`)
title: Authentication
Authentication lets you run private registries, control who can access your components, and give different teams or users different content. This guide shows common authentication patterns and how to set them up.
Authentication enables these use cases:
- Private Components: Keep your business logic and internal components secure
- Team-Specific Resources: Give different teams different components
- Access Control: Limit who can see sensitive or experimental components
- Usage Analytics: See who's using which components in your organization
- Licensing: Control who gets premium or licensed components
Common Authentication Patterns
Token-Based Authentication
The most common approach uses Bearer tokens or API keys:
{
"registries": {
"@private": {
"url": "https://registry.company.com/{name}.json",
"headers": {
"Authorization": "Bearer ${REGISTRY_TOKEN}"
}
}
}
}Set your token in environment variables:
REGISTRY_TOKEN=your_secret_token_hereAPI Key Authentication
Some registries use API keys in headers:
{
"registries": {
"@company": {
"url": "https://api.company.com/registry/{name}.json",
"headers": {
"X-API-Key": "${API_KEY}",
"X-Workspace-Id": "${WORKSPACE_ID}"
}
}
}
}Query Parameter Authentication
For simpler setups, use query parameters:
{
"registries": {
"@internal": {
"url": "https://registry.company.com/{name}.json",
"params": {
"token": "${ACCESS_TOKEN}"
}
}
}
}This creates: https://registry.company.com/button.json?token=your_token
Server-Side Implementation
Here's how to add authentication to your registry server:
Next.js API Route Example
import { NextRequest, NextResponse } from "next/server"
export async function GET(
request: NextRequest,
{ params }: { params: { name: string } }
) {
// Get token from Authorization header.
const authHeader = request.headers.get("authorization")
const token = authHeader?.replace("Bearer ", "")
// Or from query parameters.
const queryToken = request.nextUrl.searchParams.get("token")
// Check if token is valid.
if (!isValidToken(token || queryToken)) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
}
// Check if token can access this component.
if (!hasAccessToComponent(token, params.name)) {
return NextResponse.json({ error: "Forbidden" }, { status: 403 })
}
// Return the component.
const component = await getComponent(params.name)
return NextResponse.json(component)
}
function isValidToken(token: string | null) {
// Add your token validation logic here.
// Check against database, JWT validation, etc.
return token === process.env.VALID_TOKEN
}
function hasAccessToComponent(token: string, componentName: string) {
// Add role-based access control here.
// Check if token can access specific component.
return true // Your logic here.
}Express.js Example
app.get("/registry/:name.json", (req, res) => {
const token = req.headers.authorization?.replace("Bearer ", "")
if (!isValidToken(token)) {
return res.status(401).json({ error: "Unauthorized" })
}
const component = getComponent(req.params.name)
if (!component) {
return res.status(404).json({ error: "Component not found" })
}
res.json(component)
})Advanced Authentication Patterns
Team-Based Access
Give different teams different components:
async function GET(request: NextRequest) {
const token = extractToken(request)
const team = await getTeamFromToken(token)
// Get components for this team.
const components = await getComponentsForTeam(team)
return NextResponse.json(components)
}User-Personalized Registries
Give users components based on their preferences:
async function GET(request: NextRequest) {
const user = await authenticateUser(request)
// Get user's style and framework preferences.
const preferences = await getUserPreferences(user.id)
// Get personalized component version.
const component = await getPersonalizedComponent(params.name, preferences)
return NextResponse.json(component)
}Temporary Access Tokens
Use expiring tokens for better security:
interface TemporaryToken {
token: string
expiresAt: Date
scope: string[]
}
async function validateTemporaryToken(token: string) {
const tokenData = await getTokenData(token)
if (!tokenData) return false
if (new Date() > tokenData.expiresAt) return false
return true
}Multi-Registry Authentication
With namespaced registries, you can set up multiple registries with different authentication:
{
"registries": {
"@public": "https://public.company.com/{name}.json",
"@internal": {
"url": "https://internal.company.com/{name}.json",
"headers": {
"Authorization": "Bearer ${INTERNAL_TOKEN}"
}
},
"@premium": {
"url": "https://premium.company.com/{name}.json",
"headers": {
"X-License-Key": "${LICENSE_KEY}"
}
}
}
}This lets you:
- Mix public and private registries
- Use different authentication per registry
- Organize components by access level
Security Best Practices
Use Environment Variables
Never commit tokens to version control. Always use environment variables:
REGISTRY_TOKEN=your_secret_token_here
API_KEY=your_api_key_hereThen reference them in components.json:
{
"registries": {
"@private": {
"url": "https://registry.company.com/{name}.json",
"headers": {
"Authorization": "Bearer ${REGISTRY_TOKEN}"
}
}
}
}Use HTTPS
Always use HTTPS URLs for registries to protect your tokens in transit:
{
"@secure": "https://registry.company.com/{name}.json" // ✅
"@insecure": "http://registry.company.com/{name}.json" // ❌
}Add Rate Limiting
Protect your registry from abuse:
import rateLimit from "express-rate-limit"
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs
})
app.use("/registry", limiter)Rotate Tokens
Change access tokens regularly:
// Create new token with expiration.
function generateToken() {
const token = crypto.randomBytes(32).toString("hex")
const expiresAt = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000) // 30 days.
return { token, expiresAt }
}Log Access
Track registry access for security and analytics:
async function logAccess(request: Request, component: string, userId: string) {
await db.accessLog.create({
timestamp: new Date(),
userId,
component,
ip: request.ip,
userAgent: request.headers["user-agent"],
})
}Testing Authentication
Test your authenticated registry locally:
# Test with curl.
curl -H "Authorization: Bearer your_token" \
https://registry.company.com/button.json
# Test with the CLI.
REGISTRY_TOKEN=your_token npx shadcn@latest add @private/buttonError Handling
The shadcn CLI handles authentication errors gracefully:
- 401 Unauthorized: Token is invalid or missing
- 403 Forbidden: Token lacks permission for this resource
- 429 Too Many Requests: Rate limit exceeded
Custom Error Messages
Your registry server can return custom error messages in the response body, and the CLI will display them to users:
// Registry server returns custom error
return NextResponse.json(
{
error: "Unauthorized",
message:
"Your subscription has expired. Please renew at company.com/billing",
},
{ status: 403 }
)The user will see:
Your subscription has expired. Please renew at company.com/billingThis helps provide context-specific guidance:
// Different error messages for different scenarios
if (!token) {
return NextResponse.json(
{
error: "Unauthorized",
message:
"Authentication required. Set REGISTRY_TOKEN in your .env.local file",
},
{ status: 401 }
)
}
if (isExpiredToken(token)) {
return NextResponse.json(
{
error: "Unauthorized",
message: "Token expired. Request a new token at company.com/tokens",
},
{ status: 401 }
)
}
if (!hasTeamAccess(token, component)) {
return NextResponse.json(
{
error: "Forbidden",
message: `Component '${component}' is restricted to the Design team`,
},
{ status: 403 }
)
}Next Steps
To set up authentication with multiple registries and advanced patterns, see the Namespaced Registries documentation. It covers:
- Setting up multiple authenticated registries
- Using different authentication per namespace
- Cross-registry dependency resolution
- Advanced authentication patterns
Apps V4 Content Docs Registry Examples (`apps/v4/content/docs/registry/examples.mdx`)
title: Examples
registry:style
Custom style that extends shadcn/ui
The following registry item is a custom style that extends shadcn/ui. On npx shadcn init, it will:
- Install
@tabler/icons-reactas a dependency. - Add the
login-01block andcalendarcomponent to the project. - Add the
editorfrom a remote registry. - Set the
font-sansvariable toInter, sans-serif. - Install a
brandcolor in light and dark mode.
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "example-style",
"type": "registry:style",
"dependencies": ["@tabler/icons-react"],
"registryDependencies": [
"login-01",
"calendar",
"https://example.com/r/editor.json"
],
"cssVars": {
"theme": {
"font-sans": "Inter, sans-serif"
},
"light": {
"brand": "20 14.3% 4.1%"
},
"dark": {
"brand": "20 14.3% 4.1%"
}
}
}Custom style from scratch
The following registry item is a custom style that doesn't extend shadcn/ui. See the extends: none field.
It can be used to create a new style from scratch, i.e. custom components, css vars, dependencies, etc.
On npx shadcn add, the following will:
- Install
tailwind-mergeandclsxas dependencies. - Add the
utilsregistry item from the shadcn/ui registry. - Add the
button,input,label, andselectcomponents from a remote registry. - Install new css vars:
main,bg,border,text,ring.
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"extends": "none",
"name": "new-style",
"type": "registry:style",
"dependencies": ["tailwind-merge", "clsx"],
"registryDependencies": [
"utils",
"https://example.com/r/button.json",
"https://example.com/r/input.json",
"https://example.com/r/label.json",
"https://example.com/r/select.json"
],
"cssVars": {
"theme": {
"font-sans": "Inter, sans-serif"
},
"light": {
"main": "#88aaee",
"bg": "#dfe5f2",
"border": "#000",
"text": "#000",
"ring": "#000"
},
"dark": {
"main": "#88aaee",
"bg": "#272933",
"border": "#000",
"text": "#e6e6e6",
"ring": "#fff"
}
}
}registry:theme
Custom theme
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "custom-theme",
"type": "registry:theme",
"cssVars": {
"light": {
"background": "oklch(1 0 0)",
"foreground": "oklch(0.141 0.005 285.823)",
"primary": "oklch(0.546 0.245 262.881)",
"primary-foreground": "oklch(0.97 0.014 254.604)",
"ring": "oklch(0.746 0.16 232.661)",
"sidebar-primary": "oklch(0.546 0.245 262.881)",
"sidebar-primary-foreground": "oklch(0.97 0.014 254.604)",
"sidebar-ring": "oklch(0.746 0.16 232.661)"
},
"dark": {
"background": "oklch(1 0 0)",
"foreground": "oklch(0.141 0.005 285.823)",
"primary": "oklch(0.707 0.165 254.624)",
"primary-foreground": "oklch(0.97 0.014 254.604)",
"ring": "oklch(0.707 0.165 254.624)",
"sidebar-primary": "oklch(0.707 0.165 254.624)",
"sidebar-primary-foreground": "oklch(0.97 0.014 254.604)",
"sidebar-ring": "oklch(0.707 0.165 254.624)"
}
}
}Custom colors
The following style will init using shadcn/ui defaults and then add a custom brand color.
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "custom-style",
"type": "registry:style",
"cssVars": {
"light": {
"brand": "oklch(0.99 0.00 0)"
},
"dark": {
"brand": "oklch(0.14 0.00 286)"
}
}
}registry:block
Custom block
This block installs the login-01 block from the shadcn/ui registry.
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "login-01",
"type": "registry:block",
"description": "A simple login form.",
"registryDependencies": ["button", "card", "input", "label"],
"files": [
{
"path": "blocks/login-01/page.tsx",
"content": "import { LoginForm } ...",
"type": "registry:page",
"target": "app/login/page.tsx"
},
{
"path": "blocks/login-01/components/login-form.tsx",
"content": "...",
"type": "registry:component"
}
]
}Install a block and override primitives
You can install a block from the shadcn/ui registry and override the primitives using your custom ones.
On npx shadcn add, the following will:
- Add the
login-01block from the shadcn/ui registry. - Override the
button,input, andlabelprimitives with the ones from the remote registry.
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "custom-login",
"type": "registry:block",
"registryDependencies": [
"login-01",
"https://example.com/r/button.json",
"https://example.com/r/input.json",
"https://example.com/r/label.json"
]
}registry:ui
UI component
A registry:ui item is a reusable UI component. It can have dependencies, registry dependencies, and CSS variables.
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "button",
"type": "registry:ui",
"dependencies": ["radix-ui"],
"files": [
{
"path": "ui/button.tsx",
"content": "...",
"type": "registry:ui"
}
]
}UI component with CSS variables
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "sidebar",
"type": "registry:ui",
"dependencies": ["radix-ui"],
"registryDependencies": ["button", "separator", "sheet", "tooltip"],
"files": [
{
"path": "ui/sidebar.tsx",
"content": "...",
"type": "registry:ui"
}
],
"cssVars": {
"light": {
"sidebar-background": "oklch(0.985 0 0)",
"sidebar-foreground": "oklch(0.141 0.005 285.823)",
"sidebar-border": "oklch(0.92 0.004 286.32)"
},
"dark": {
"sidebar-background": "oklch(0.141 0.005 285.823)",
"sidebar-foreground": "oklch(0.985 0 0)",
"sidebar-border": "oklch(0.274 0.006 286.033)"
}
}
}registry:lib
Utility library
A registry:lib item is a utility library. Use it to share helper functions, constants, or other non-component code.
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "utils",
"type": "registry:lib",
"dependencies": ["clsx", "tailwind-merge"],
"files": [
{
"path": "lib/utils.ts",
"content": "import { clsx, type ClassValue } from \"clsx\"\nimport { twMerge } from \"tailwind-merge\"\n\nexport function cn(...inputs: ClassValue[]) {\n return twMerge(clsx(inputs))\n}",
"type": "registry:lib"
}
]
}registry:hook
Custom hook
A registry:hook item is a custom React hook.
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "use-mobile",
"type": "registry:hook",
"files": [
{
"path": "hooks/use-mobile.ts",
"content": "...",
"type": "registry:hook"
}
]
}Hook with dependencies
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "use-debounce",
"type": "registry:hook",
"dependencies": ["react"],
"files": [
{
"path": "hooks/use-debounce.ts",
"content": "...",
"type": "registry:hook"
}
]
}registry:font
Custom font
A registry:font item installs a Google Font. The font field is required and configures the font family, provider, import name, and CSS variable.
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "font-inter",
"type": "registry:font",
"font": {
"family": "'Inter Variable', sans-serif",
"provider": "google",
"import": "Inter",
"variable": "--font-sans",
"subsets": ["latin"],
"dependency": "@fontsource-variable/inter"
}
}Monospace font
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "font-jetbrains-mono",
"type": "registry:font",
"font": {
"family": "'JetBrains Mono Variable', monospace",
"provider": "google",
"import": "JetBrains_Mono",
"variable": "--font-mono",
"weight": ["400", "500", "600", "700"],
"subsets": ["latin"],
"dependency": "@fontsource-variable/jetbrains-mono"
}
}Serif font
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "font-lora",
"type": "registry:font",
"font": {
"family": "'Lora Variable', serif",
"provider": "google",
"import": "Lora",
"variable": "--font-serif",
"subsets": ["latin"],
"dependency": "@fontsource-variable/lora"
}
}Font with custom selector
Use the selector field to apply a font to specific CSS selectors instead of globally on html. This is useful for heading fonts or other targeted font applications.
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "font-playfair-display",
"type": "registry:font",
"font": {
"family": "'Playfair Display Variable', serif",
"provider": "google",
"import": "Playfair_Display",
"variable": "--font-heading",
"subsets": ["latin"],
"selector": "h1, h2, h3, h4, h5, h6",
"dependency": "@fontsource-variable/playfair-display"
}
}When selector is set, the font utility class (e.g. font-heading) is applied via CSS @apply on the specified selector within @layer base, instead of being added to the <html> element. The CSS variable is still injected on <html> so it's available globally.
registry:base
Custom base
A registry:base item is a complete design system base. It defines the full set of dependencies, CSS variables, and configuration for a project. The config field is unique to registry:base items.
The config field accepts the following properties (all optional):
| Property | Type | Description |
|---|---|---|
style |
string |
The style name for the base. |
iconLibrary |
string |
The icon library to use (e.g. lucide). |
rsc |
boolean |
Whether to enable React Server Components. Defaults to false. |
tsx |
boolean |
Whether to use TypeScript. Defaults to true. |
rtl |
boolean |
Whether to enable right-to-left support. Defaults to false. |
menuColor |
"default" | "inverted" | "default-translucent" | "inverted-translucent" |
The menu color scheme. Defaults to "default". |
menuAccent |
"subtle" | "bold" |
The menu accent style. Defaults to "subtle". |
tailwind.baseColor |
string |
The base color name (e.g. neutral, slate, zinc). |
tailwind.css |
string |
Path to the Tailwind CSS file. |
tailwind.prefix |
string |
A prefix to add to all Tailwind classes. |
aliases.components |
string |
Import alias for components. |
aliases.utils |
string |
Import alias for utilities. |
aliases.ui |
string |
Import alias for UI components. |
aliases.lib |
string |
Import alias for lib. |
aliases.hooks |
string |
Import alias for hooks. |
registries |
Record<string, string | object> |
Custom registry URLs. Keys must start with @. |
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "custom-base",
"type": "registry:base",
"config": {
"style": "custom-base",
"iconLibrary": "lucide",
"tailwind": {
"baseColor": "neutral"
}
},
"dependencies": [
"class-variance-authority",
"tw-animate-css",
"lucide-react"
],
"registryDependencies": ["utils", "font-inter"],
"cssVars": {
"light": {
"background": "oklch(1 0 0)",
"foreground": "oklch(0.141 0.005 285.823)",
"primary": "oklch(0.21 0.006 285.885)",
"primary-foreground": "oklch(0.985 0 0)"
},
"dark": {
"background": "oklch(0.141 0.005 285.823)",
"foreground": "oklch(0.985 0 0)",
"primary": "oklch(0.985 0 0)",
"primary-foreground": "oklch(0.21 0.006 285.885)"
}
},
"css": {
"@import \"tw-animate-css\"": {},
"@layer base": {
"*": {
"@apply border-border outline-ring/50": {}
},
"body": {
"@apply bg-background text-foreground": {}
}
}
}
}Base from scratch
Use extends: none to create a base that doesn't extend shadcn/ui defaults.
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "my-design-system",
"extends": "none",
"type": "registry:base",
"config": {
"style": "my-design-system",
"iconLibrary": "lucide",
"tailwind": {
"baseColor": "slate"
}
},
"dependencies": ["tailwind-merge", "clsx", "tw-animate-css", "lucide-react"],
"registryDependencies": ["utils", "font-geist"],
"cssVars": {
"light": {
"background": "oklch(1 0 0)",
"foreground": "oklch(0.141 0.005 285.823)"
},
"dark": {
"background": "oklch(0.141 0.005 285.823)",
"foreground": "oklch(0.985 0 0)"
}
}
}Common Fields
Author
Use the author field to add attribution to your registry items.
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "custom-component",
"type": "registry:ui",
"author": "shadcn",
"files": [
{
"path": "ui/custom-component.tsx",
"content": "...",
"type": "registry:ui"
}
]
}Dev dependencies
Use the devDependencies field to install packages as dev dependencies.
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "custom-item",
"type": "registry:item",
"devDependencies": ["@types/mdx"],
"files": [
{
"path": "lib/mdx.ts",
"content": "...",
"type": "registry:lib"
}
]
}Metadata
Use the meta field to attach arbitrary metadata to your registry items. This can be used to store custom data that your tools or scripts can use.
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "custom-component",
"type": "registry:ui",
"meta": {
"category": "forms",
"version": "2.0.0"
},
"files": [
{
"path": "ui/custom-component.tsx",
"content": "...",
"type": "registry:ui"
}
]
}CSS Variables
Custom Theme Variables
Add custom theme variables to the theme object.
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "custom-theme",
"type": "registry:theme",
"cssVars": {
"theme": {
"font-heading": "Inter, sans-serif",
"shadow-card": "0 0 0 1px rgba(0, 0, 0, 0.1)"
}
}
}Override Tailwind CSS variables
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "custom-theme",
"type": "registry:theme",
"cssVars": {
"theme": {
"spacing": "0.2rem",
"breakpoint-sm": "640px",
"breakpoint-md": "768px",
"breakpoint-lg": "1024px",
"breakpoint-xl": "1280px",
"breakpoint-2xl": "1536px"
}
}
}Add custom CSS
Base styles
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "custom-style",
"type": "registry:style",
"css": {
"@layer base": {
"h1": {
"font-size": "var(--text-2xl)"
},
"h2": {
"font-size": "var(--text-xl)"
}
}
}
}Components
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "custom-card",
"type": "registry:component",
"css": {
"@layer components": {
"card": {
"background-color": "var(--color-white)",
"border-radius": "var(--rounded-lg)",
"padding": "var(--spacing-6)",
"box-shadow": "var(--shadow-xl)"
}
}
}
}Add custom utilities
Simple utility
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "custom-component",
"type": "registry:component",
"css": {
"@utility content-auto": {
"content-visibility": "auto"
}
}
}Complex utility
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "custom-component",
"type": "registry:component",
"css": {
"@utility scrollbar-hidden": {
"scrollbar-hidden": {
"&::-webkit-scrollbar": {
"display": "none"
}
}
}
}
}Functional utilities
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "custom-component",
"type": "registry:component",
"css": {
"@utility tab-*": {
"tab-size": "var(--tab-size-*)"
}
}
}Add CSS imports
Use @import to add CSS imports to your registry item. The imports will be placed at the top of the CSS file.
Basic import
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "custom-import",
"type": "registry:component",
"css": {
"@import \"tailwindcss\"": {},
"@import \"./styles/base.css\"": {}
}
}Import with url() syntax
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "font-import",
"type": "registry:item",
"css": {
"@import url(\"https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap\")": {},
"@import url('./local-styles.css')": {}
}
}Import with media queries
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "responsive-import",
"type": "registry:item",
"css": {
"@import \"print-styles.css\" print": {},
"@import url(\"mobile.css\") screen and (max-width: 768px)": {}
}
}Add custom plugins
Use @plugin to add Tailwind plugins to your registry item. Plugins will be automatically placed after imports and before other content.
Important: When using plugins from npm packages, you must also add them to the dependencies array.
Basic plugin usage
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "custom-plugin",
"type": "registry:item",
"css": {
"@plugin \"@tailwindcss/typography\"": {},
"@plugin \"foo\"": {}
}
}Plugin with npm dependency
When using plugins from npm packages like @tailwindcss/typography, include them in the dependencies.
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "typography-component",
"type": "registry:item",
"dependencies": ["@tailwindcss/typography"],
"css": {
"@plugin \"@tailwindcss/typography\"": {},
"@layer components": {
".prose": {
"max-width": "65ch"
}
}
}
}Scoped and file-based plugins
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "scoped-plugins",
"type": "registry:component",
"css": {
"@plugin \"@headlessui/tailwindcss\"": {},
"@plugin \"tailwindcss/plugin\"": {},
"@plugin \"./custom-plugin.js\"": {}
}
}Multiple plugins with automatic ordering
When you add multiple plugins, they are automatically grouped together and deduplicated.
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "multiple-plugins",
"type": "registry:item",
"dependencies": [
"@tailwindcss/typography",
"@tailwindcss/forms",
"tw-animate-css"
],
"css": {
"@plugin \"@tailwindcss/typography\"": {},
"@plugin \"@tailwindcss/forms\"": {},
"@plugin \"tw-animate-css\"": {}
}
}Combined imports and plugins
When using both @import and @plugin directives, imports are placed first, followed by plugins, then other CSS content.
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "combined-example",
"type": "registry:item",
"dependencies": ["@tailwindcss/typography", "tw-animate-css"],
"css": {
"@import \"tailwindcss\"": {},
"@import url(\"https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap\")": {},
"@plugin \"@tailwindcss/typography\"": {},
"@plugin \"tw-animate-css\"": {},
"@layer base": {
"body": {
"font-family": "Inter, sans-serif"
}
},
"@utility content-auto": {
"content-visibility": "auto"
}
}
}Add custom animations
Note: you need to define both @keyframes in css and theme in cssVars to use animations.
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "custom-component",
"type": "registry:component",
"cssVars": {
"theme": {
"--animate-wiggle": "wiggle 1s ease-in-out infinite"
}
},
"css": {
"@keyframes wiggle": {
"0%, 100%": {
"transform": "rotate(-3deg)"
},
"50%": {
"transform": "rotate(3deg)"
}
}
}
}Add environment variables
You can add environment variables using the envVars field.
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "custom-item",
"type": "registry:item",
"envVars": {
"NEXT_PUBLIC_APP_URL": "http://localhost:4000",
"DATABASE_URL": "postgresql://postgres:postgres@localhost:5432/postgres",
"OPENAI_API_KEY": ""
}
}Environment variables are added to the .env.local or .env file. Existing variables are not overwritten.
IMPORTANT: Use envVars to add development or example variables. Do NOT use it to add production variables.
Universal Items
As of 2.9.0, you can create universal items that can be installed without framework detection or components.json.
To make an item universal i.e framework agnostic, all the files in the item must have an explicit target.
Here's an example of a registry item that installs custom Cursor rules for python:
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "python-rules",
"type": "registry:item",
"files": [
{
"path": "/path/to/your/registry/default/custom-python.mdc",
"type": "registry:file",
"target": "~/.cursor/rules/custom-python.mdc",
"content": "..."
}
]
}Here's another example for installing a custom ESLint config:
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "my-eslint-config",
"type": "registry:item",
"files": [
{
"path": "/path/to/your/registry/default/custom-eslint.json",
"type": "registry:file",
"target": "~/.eslintrc.json",
"content": "..."
}
]
}You can also have a universal item that installs multiple files:
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "my-custom-starter-template",
"type": "registry:item",
"dependencies": ["better-auth"],
"files": [
{
"path": "/path/to/file-01.json",
"type": "registry:file",
"target": "~/file-01.json",
"content": "..."
},
{
"path": "/path/to/file-02.vue",
"type": "registry:file",
"target": "~/pages/file-02.vue",
"content": "..."
}
]
}Apps V4 Content Docs Registry Faq (`apps/v4/content/docs/registry/faq.mdx`)
title: FAQ
Frequently asked questions
What does a complex component look like?
Here's an example of a complex component that installs a page, two components, a hook, a format-date utils and a config file.
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "hello-world",
"title": "Hello World",
"type": "registry:block",
"description": "A complex hello world component",
"files": [
{
"path": "registry/new-york/hello-world/page.tsx",
"type": "registry:page",
"target": "app/hello/page.tsx"
},
{
"path": "registry/new-york/hello-world/components/hello-world.tsx",
"type": "registry:component"
},
{
"path": "registry/new-york/hello-world/components/formatted-message.tsx",
"type": "registry:component"
},
{
"path": "registry/new-york/hello-world/hooks/use-hello.ts",
"type": "registry:hook"
},
{
"path": "registry/new-york/hello-world/lib/format-date.ts",
"type": "registry:lib"
},
{
"path": "registry/new-york/hello-world/hello.config.ts",
"type": "registry:file",
"target": "~/hello.config.ts"
}
]
}How do I add a new Tailwind color?
To add a new color you need to add it to cssVars under light and dark keys.
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "hello-world",
"title": "Hello World",
"type": "registry:block",
"description": "A complex hello world component",
"files": [
// ...
],
"cssVars": {
"light": {
"brand-background": "oklch(0.205 0.015 18)",
"brand-accent": "oklch(0.205 0.015 18)"
},
"dark": {
"brand-background": "oklch(0.205 0.015 18)",
"brand-accent": "oklch(0.205 0.015 18)"
}
}
}The CLI will update the project CSS file. Once updated, the new colors will be available to be used as utility classes: bg-brand and text-brand-accent.
How do I add or override a Tailwind theme variable?
To add or override a theme variable you add it to cssVars.theme under the key you want to add or override.
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "hello-world",
"title": "Hello World",
"type": "registry:block",
"description": "A complex hello world component",
"files": [
// ...
],
"cssVars": {
"theme": {
"text-base": "3rem",
"ease-in-out": "cubic-bezier(0.4, 0, 0.2, 1)",
"font-heading": "Poppins, sans-serif"
}
}
}Apps V4 Content Docs Registry Mcp (`apps/v4/content/docs/registry/mcp.mdx`)
title: MCP Server
The shadcn MCP server works out of the box with any shadcn-compatible registry. You do not need to do anything special to enable MCP support for your registry.
Prerequisites
The MCP server works by requesting your registry index. Make sure you have a registry item file at the root of your registry named registry.
For example, if your registry is hosted at https://acme.com/r/[name].json, you should have a file at https://acme.com/r/registry.json or https://acme.com/r/registry if you're using a JSON file extension.
This file must be a valid JSON file that conforms to the registry schema.
Configuring MCP
Ask your registry consumers to configure your registry in their components.json file and install the shadcn MCP server:
```json title="components.json" showLineNumbers
{
"registries": {
"@acme": "https://acme.com/r/{name}.json"
}
}
```
**Run the following command** in your project:
```bash
npx shadcn@latest mcp init --client claude
```
**Restart Claude Code** and try the following prompts:
- Show me the components in the acme registry
- Create a landing page using items from the acme registry
**Note:** You can use `/mcp` command in Claude Code to debug the MCP server.```json title="components.json" showLineNumbers
{
"registries": {
"@acme": "https://acme.com/r/{name}.json"
}
}
```
**Run the following command** in your project:
```bash
npx shadcn@latest mcp init --client cursor
```
Open **Cursor Settings** and **Enable the MCP server** for shadcn. Then try the following prompts:
- Show me the components in the acme registry
- Create a landing page using items from the acme registry```json title="components.json" showLineNumbers
{
"registries": {
"@acme": "https://acme.com/r/{name}.json"
}
}
```
**Run the following command** in your project:
```bash
npx shadcn@latest mcp init --client vscode
```
Open `.vscode/mcp.json` and click **Start** next to the shadcn server. Then try the following prompts with GitHub Copilot:
- Show me the components in the acme registry
- Create a landing page using items from the acme registry```json title="components.json" showLineNumbers
{
"registries": {
"@acme": "https://acme.com/r/{name}.json"
}
}
```
**Add the following configuration** to `~/.codex/config.toml`:
```toml
[mcp_servers.shadcn]
command = "npx"
args = ["shadcn@latest", "mcp"]
```
**Restart Codex** and try the following prompts:
- Show me the components in the acme registry
- Create a landing page using items from the acme registry```json title="components.json" showLineNumbers
{
"registries": {
"@acme": "https://acme.com/r/{name}.json"
}
}
```
**Run the following command** in your project:
```bash
npx shadcn@latest mcp init --client opencode
```
**Restart OpenCode** and try the following prompts:
- Show me the components in the acme registry
- Create a landing page using items from the acme registryYou can read more about the MCP server in the MCP documentation.
Best Practices
Here are some best practices for MCP-compatible registries:
- Clear Descriptions: Add concise, informative descriptions that help AI assistants understand what a registry item is for and how to use it.
- Proper Dependencies: List all
dependenciesaccurately so MCP can install them automatically. - Registry Dependencies: Use
registryDependenciesto indicate relationships between items. - Consistent Naming: Use kebab-case for component names and maintain consistency across your registry.
Apps V4 Content Docs Registry Meta.Json (`apps/v4/content/docs/registry/meta.json`)
{
"title": "Registry",
"pages": [
"index",
"getting-started",
"namespace",
"authentication",
"examples",
"mcp",
"registry-index",
"open-in-v0",
"registry-json",
"registry-item-json"
]
}
Apps V4 Content Docs Registry Namespace (`apps/v4/content/docs/registry/namespace.mdx`)
title: Namespaces
Namespaced registries let you configure multiple resource sources in one project. This means you can install components, libraries, utilities, AI prompts, configuration files, and other resources from various registries, whether they're public, third-party, or your own custom private libraries.
Table of Contents
- Overview
- Decentralized Namespace System
- Getting Started
- Registry Naming Convention
- Configuration
- Authentication & Security
- Versioning
- Dependency Resolution
- Built-in Registries
- CLI Commands
- Error Handling
- Creating Your Own Registry
- Example Configurations
- Technical Details
- Best Practices
- Troubleshooting
Overview
Registry namespaces are prefixed with @ and provide a way to organize and reference resources from different sources. Resources can be any type of content: components, libraries, utilities, hooks, AI prompts, configuration files, themes, and more. For example:
@shadcn/button- UI component from the shadcn registry@v0/dashboard- Dashboard component from the v0 registry@ai-elements/input- AI prompt input from an AI elements registry@acme/auth-utils- Authentication utilities from your company's private registry@ai/chatbot-rules- AI prompt rules from an AI resources registry@themes/dark-mode- Theme configuration from a themes registry
Decentralized Namespace System
We intentionally designed the namespace system to be decentralized. There is a central open source registry index for open source namespaces but you are free to create and use any namespace you want.
This decentralized approach gives you complete flexibility to organize your resources however makes sense for your organization.
You can create multiple registries for different purposes:
{
"registries": {
"@acme-ui": "https://registry.acme.com/ui/{name}.json",
"@acme-docs": "https://registry.acme.com/docs/{name}.json",
"@acme-ai": "https://registry.acme.com/ai/{name}.json",
"@acme-themes": "https://registry.acme.com/themes/{name}.json",
"@acme-internal": {
"url": "https://internal.acme.com/registry/{name}.json",
"headers": {
"Authorization": "Bearer ${INTERNAL_TOKEN}"
}
}
}
}This allows you to:
- Organize by type: Separate UI components, documentation, AI resources, etc.
- Organize by team: Different teams can maintain their own registries
- Organize by visibility: Public vs. private resources
- Organize by version: Stable vs. experimental registries
- No naming conflicts: Since there's no central authority, you don't need to worry about namespace collisions
Examples of Multi-Registry Setups
By Resource Type
{
"@components": "https://cdn.company.com/components/{name}.json",
"@hooks": "https://cdn.company.com/hooks/{name}.json",
"@utils": "https://cdn.company.com/utils/{name}.json",
"@prompts": "https://cdn.company.com/ai-prompts/{name}.json"
}By Team or Department
{
"@design": "https://create.company.com/registry/{name}.json",
"@engineering": "https://eng.company.com/registry/{name}.json",
"@marketing": "https://marketing.company.com/registry/{name}.json"
}By Stability
{
"@stable": "https://registry.company.com/stable/{name}.json",
"@latest": "https://registry.company.com/beta/{name}.json",
"@experimental": "https://registry.company.com/experimental/{name}.json"
}Getting Started
Installing Resources
Once configured, you can install resources using the namespace syntax:
npx shadcn@latest add @v0/dashboardor multiple resources at once:
npx shadcn@latest add @acme/header @lib/auth-utils @ai/chatbot-rulesQuick Configuration
Add registries to your components.json:
{
"registries": {
"@v0": "https://v0.dev/chat/b/{name}",
"@acme": "https://registry.acme.com/resources/{name}.json"
}
}Then start installing:
npx shadcn@latest add @acme/buttonRegistry Naming Convention
Registry names must follow these rules:
- Start with
@symbol - Contain only alphanumeric characters, hyphens, and underscores
- Examples of valid names:
@v0,@acme-ui,@my_company
The pattern for referencing resources is: @namespace/resource-name
Configuration
Namespaced registries are configured in your components.json file under the registries field.
Basic Configuration
The simplest way to configure a registry is with a URL template string:
{
"registries": {
"@v0": "https://v0.dev/chat/b/{name}",
"@acme": "https://registry.acme.com/resources/{name}.json",
"@lib": "https://lib.company.com/utilities/{name}",
"@ai": "https://ai-resources.com/r/{name}.json"
}
}Note: The
{name}placeholder in the URL is automatically parsed and replaced with the resource name when you runnpx shadcn@latest add @namespace/resource-name. For example,@acme/buttonbecomeshttps://registry.acme.com/resources/button.json. See URL Pattern System for more details.
Advanced Configuration
For registries that require authentication or additional parameters, use the object format:
{
"registries": {
"@private": {
"url": "https://api.company.com/registry/{name}.json",
"headers": {
"Authorization": "Bearer ${REGISTRY_TOKEN}",
"X-API-Key": "${API_KEY}"
},
"params": {
"version": "latest",
"format": "json"
}
}
}
}Note: Environment variables in the format
${VAR_NAME}are automatically expanded from your environment (process.env). This works in URLs, headers, and params. For example,${REGISTRY_TOKEN}will be replaced with the value ofprocess.env.REGISTRY_TOKEN. See Authentication & Security for more details on using environment variables.
URL Pattern System
Registry URLs support the following placeholders:
`{name}` Placeholder (required)
The {name} placeholder is replaced with the resource name:
{
"@acme": "https://registry.acme.com/{name}.json"
}When installing @acme/button, the URL becomes: https://registry.acme.com/button.json
When installing @acme/auth-utils, the URL becomes: https://registry.acme.com/auth-utils.json
`{style}` Placeholder (optional)
The {style} placeholder is replaced with the current style configuration:
{
"@themes": "https://registry.example.com/{style}/{name}.json"
}With style set to new-york, installing @themes/card resolves to: https://registry.example.com/new-york/card.json
The style placeholder is optional. Use this when you want to serve different versions of the same resource. For example, you can serve a different version of a component for each style.
Authentication & Security
Environment Variables
Use environment variables to securely store credentials:
{
"registries": {
"@private": {
"url": "https://api.company.com/registry/{name}.json",
"headers": {
"Authorization": "Bearer ${REGISTRY_TOKEN}"
}
}
}
}Then set the environment variable:
REGISTRY_TOKEN=your_secret_token_hereAuthentication Methods
Bearer Token (OAuth 2.0)
{
"@github": {
"url": "https://api.github.com/repos/org/registry/contents/{name}.json",
"headers": {
"Authorization": "Bearer ${GITHUB_TOKEN}"
}
}
}API Key in Headers
{
"@private": {
"url": "https://api.company.com/registry/{name}",
"headers": {
"X-API-Key": "${API_KEY}"
}
}
}Basic Authentication
{
"@internal": {
"url": "https://registry.company.com/{name}.json",
"headers": {
"Authorization": "Basic ${BASE64_CREDENTIALS}"
}
}
}Query Parameter Authentication
{
"@secure": {
"url": "https://registry.example.com/{name}.json",
"params": {
"api_key": "${API_KEY}",
"client_id": "${CLIENT_ID}",
"signature": "${REQUEST_SIGNATURE}"
}
}
}Multiple Authentication Methods
Some registries require multiple authentication methods:
{
"@enterprise": {
"url": "https://api.enterprise.com/v2/registry/{name}",
"headers": {
"Authorization": "Bearer ${ACCESS_TOKEN}",
"X-API-Key": "${API_KEY}",
"X-Workspace-Id": "${WORKSPACE_ID}"
},
"params": {
"version": "latest"
}
}
}Security Considerations
When working with namespaced registries, especially third-party or public ones, security is paramount. Here's how we handle security:
Resource Validation
All resources fetched from registries are validated against our registry item schema before installation. This ensures:
- Structure validation: Resources must conform to the expected JSON schema
- Type safety: Resource types are validated (
registry:ui,registry:lib, etc.) - No arbitrary code execution: Resources are data files, not executable scripts
Environment Variable Security
Environment variables used for authentication are:
- Never logged: The CLI never logs or displays environment variable values
- Expanded at runtime: Variables are only expanded when needed, not stored
- Isolated per registry: Each registry maintains its own authentication context
Example of secure configuration:
{
"registries": {
"@private": {
"url": "https://api.company.com/registry/{name}.json",
"headers": {
"Authorization": "Bearer ${PRIVATE_REGISTRY_TOKEN}"
}
}
}
}Never commit actual tokens to version control. Use .env.local:
PRIVATE_REGISTRY_TOKEN=actual_token_hereHTTPS Enforcement
We strongly recommend using HTTPS for all registry URLs:
- Encrypted transport: Prevents man-in-the-middle attacks
- Certificate validation: Ensures you're connecting to the legitimate registry
- Credential protection: Headers and tokens are encrypted in transit
{
"registries": {
"@secure": "https://registry.example.com/{name}.json", // ✅ Good
"@insecure": "http://registry.example.com/{name}.json" // ❌ Avoid
}
}Content Security
Resources from registries are treated as data, not code:
- JSON parsing only: Resources must be valid JSON
- Schema validation: Must match the registry item schema
- File path restrictions: Files can only be written to configured paths
- No script execution: The CLI doesn't execute any code from registry resources
Registry Trust Model
The namespace system operates on a trust model:
- You trust what you install: Only add registries you trust to your configuration
- Explicit configuration: Registries must be explicitly configured in
components.json - No automatic registry discovery: The CLI never automatically adds registries
- Dependency transparency: All dependencies are clearly listed in registry items
Best Practices for Registry Operators
If you're running your own registry:
- Use HTTPS always: Never serve registry content over HTTP
- Implement authentication: Require API keys or tokens for private registries
- Rate limiting: Protect your registry from abuse
- Content validation: Validate resources before serving them
Example secure registry setup:
{
"@company": {
"url": "https://registry.company.com/v1/{name}.json",
"headers": {
"Authorization": "Bearer ${COMPANY_TOKEN}",
"X-Registry-Version": "1.0"
}
}
}Inspecting Resources Before Installation
The CLI provides transparency about what's being installed. You can see the payload of a registry item using the following command:
npx shadcn@latest view @acme/buttonThis will output the payload of the registry item to the console.
Dependency Resolution
Basic Dependency Resolution
Resources can have dependencies across different registries:
{
"name": "dashboard",
"type": "registry:block",
"registryDependencies": [
"@shadcn/card", // From default registry
"@v0/chart", // From v0 registry
"@acme/data-table", // From acme registry
"@lib/data-fetcher", // Utility library
"@ai/analytics-prompt" // AI prompt resource
]
}The CLI automatically resolves and installs all dependencies from their respective registries.
Advanced Dependency Resolution
Understanding how dependencies are resolved internally is important if you're developing registries or need to customize third-party resources.
How Resolution Works
When you run npx shadcn@latest add @namespace/resource, the CLI does the following:
- Clears registry context to start fresh
- Fetches the main resource from the specified registry
- Recursively resolves dependencies from their respective registries
- Applies topological sorting to ensure proper installation order
- Deduplicates files based on target paths (last one wins)
- Deep merges configurations (tailwind, cssVars, css, envVars)
This means that if you run the following command:
npx shadcn@latest add @acme/auth @custom/login-formThe login-form.ts from @custom/login-form will override the login-form.ts from @acme/auth because it's resolved last.
Overriding Third-Party Resources
You can leverage the dependency resolution process to override any third-party resource by adding them to your custom resource under registryDependencies and overriding with your own custom values.
Example: Customizing a Third-Party Button
Let's say you want to customize a button from a vendor registry:
1. Original vendor button (@vendor/button):
{
"name": "button",
"type": "registry:ui",
"files": [
{
"path": "components/ui/button.tsx",
"type": "registry:ui",
"content": "// Vendor's button implementation\nexport function Button() { ... }"
}
],
"cssVars": {
"light": {
"--button-bg": "blue"
}
}
}2. Create your custom override (@my-company/custom-button):
{
"name": "custom-button",
"type": "registry:ui",
"registryDependencies": [
"@vendor/button" // Import original first
],
"cssVars": {
"light": {
"--button-bg": "purple" // Override the color
}
}
}3. Install your custom version:
npx shadcn@latest add @my-company/custom-buttonThis installs the original button from @vendor/button and then overrides the cssVars with your own custom values.
Advanced Override Patterns
Extending Without Replacing
Keep the original and add extensions:
{
"name": "extended-table",
"registryDependencies": ["@vendor/table"],
"files": [
{
"path": "components/ui/table-extended.tsx",
"content": "import { Table } from '@vendor/table'\n// Add your extensions\nexport function ExtendedTable() { ... }"
}
]
}This will install the original table from @vendor/table and then add your extensions to components/ui/table-extended.tsx.
Partial Override (Multi-file Resources)
Override only specific files from a complex component:
{
"name": "custom-auth",
"registryDependencies": [
"@vendor/auth" // Has multiple files
],
"files": [
{
"path": "lib/auth-server.ts",
"type": "registry:lib",
"content": "// Your custom auth server"
}
]
}Resolution Order Example
When you install @custom/dashboard that depends on multiple resources:
{
"name": "dashboard",
"registryDependencies": [
"@shadcn/card", // 1. Resolved first
"@vendor/chart", // 2. Resolved second
"@custom/card" // 3. Resolved last (overrides @shadcn/card)
]
}Resolution order:
@shadcn/card- installs tocomponents/ui/card.tsx@vendor/chart- installs tocomponents/ui/chart.tsx@custom/card- overwritescomponents/ui/card.tsx(if same target)
Key Resolution Features
- Source Tracking: Each resource knows which registry it came from, avoiding naming conflicts
- Circular Dependency Prevention: Automatically detects and prevents circular dependencies
- Smart Installation Order: Dependencies are installed first, then the resources that use them
Versioning
You can implement versioning for your registry resources using query parameters. This allows users to pin specific versions or use different release channels.
Basic Version Parameter
{
"@versioned": {
"url": "https://registry.example.com/{name}",
"params": {
"version": "v2"
}
}
}This resolves @versioned/button to: https://registry.example.com/button?version=v2
Dynamic Version Selection
Use environment variables to control versions across your project:
{
"@stable": {
"url": "https://registry.company.com/{name}",
"params": {
"version": "${REGISTRY_VERSION}"
}
}
}This allows you to:
- Set
REGISTRY_VERSION=v1.2.3in production - Override per environment (dev, staging, prod)
Semantic Versioning
Implement semantic versioning with range support:
{
"@npm-style": {
"url": "https://registry.example.com/{name}",
"params": {
"semver": "^2.0.0",
"prerelease": "${ALLOW_PRERELEASE}"
}
}
}Version Resolution Best Practices
- Use environment variables for version control across environments
- Provide sensible defaults using the
${VAR:-default}syntax - Document version schemes clearly for registry users
- Support version pinning for reproducible builds
- Implement version discovery endpoints (e.g.,
/versions/{name}) - Cache versioned resources appropriately with proper cache headers
CLI Commands
The shadcn CLI provides several commands for working with namespaced registries:
Adding Resources
Install resources from any configured registry:
# Install from a specific registry
npx shadcn@latest add @v0/dashboard
# Install multiple resources
npx shadcn@latest add @acme/button @lib/utils @ai/prompt
# Install from URL directly
npx shadcn@latest add https://registry.example.com/button.json
# Install from local file
npx shadcn@latest add ./local-registry/button.jsonViewing Resources
Inspect registry items before installation:
# View a resource from a registry
npx shadcn@latest view @acme/button
# View multiple resources
npx shadcn@latest view @v0/dashboard @shadcn/card
# View from URL
npx shadcn@latest view https://registry.example.com/button.jsonThe view command displays:
- Resource metadata (name, type, description)
- Dependencies and registry dependencies
- File contents that will be installed
- CSS variables and Tailwind configuration
- Required environment variables
Searching Registries
Search for available resources in registries:
# Search a specific registry
npx shadcn@latest search @v0
# Search with query
npx shadcn@latest search @acme --query "auth"
# Search multiple registries
npx shadcn@latest search @v0 @acme @lib
# Limit results
npx shadcn@latest search @v0 --limit 10 --offset 20
# List all items (alias for search)
npx shadcn@latest list @acmeSearch results include:
- Resource name and type
- Description
- Registry source
Error Handling
Registry Not Configured
If you reference a registry that isn't configured:
npx shadcn@latest add @non-existent/componentError:
Unknown registry "@non-existent". Make sure it is defined in components.json as follows:
{
"registries": {
"@non-existent": "[URL_TO_REGISTRY]"
}
}Missing Environment Variables
If required environment variables are not set:
Registry "@private" requires the following environment variables:
• REGISTRY_TOKEN
Set the required environment variables to your .env or .env.local file.Resource Not Found
404 Not Found:
The item at https://registry.company.com/button.json was not found. It may not exist at the registry.This usually means:
- The resource name is misspelled
- The resource doesn't exist in the registry
- The registry URL pattern is incorrect
Authentication Failures
401 Unauthorized:
You are not authorized to access the item at https://api.company.com/button.json
Check your authentication credentials and environment variables.403 Forbidden:
Access forbidden for https://api.company.com/button.json
Verify your API key has the necessary permissions.Creating Your Own Registry
To make your registry compatible with the namespace system, you can serve any type of resource - components, libraries, utilities, AI prompts, themes, configurations, or any other shareable code/content:
Implement the registry item schema: Your registry must return JSON that conforms to the registry item schema.
Support the URL pattern: Include
{name}in your URL template where the resource name will be inserted.Define resource types: Use appropriate
typefields to identify your resources (e.g.,registry:ui,registry:lib,registry:ai,registry:theme, etc.).Handle authentication (if needed): Accept authentication via headers or query parameters.
Document your namespace: Provide clear instructions for users to configure your registry:
{
"registries": {
"@your-registry": "https://your-domain.com/r/{name}.json"
}
}Technical Details
Parser Pattern
The namespace parser uses the following regex pattern:
/^(@[a-zA-Z0-9](?:[a-zA-Z0-9-_]*[a-zA-Z0-9])?)\/(.+)$/This ensures valid namespace formatting and proper component name extraction.
Resolution Process
- Parse: Extract namespace and component name from
@namespace/component - Lookup: Find registry configuration for
@namespace - Build URL: Replace placeholders with actual values
- Set Headers: Apply authentication headers if configured
- Fetch: Retrieve component from the resolved URL
- Validate: Ensure response matches registry item schema
- Resolve Dependencies: Recursively fetch any registry dependencies
Cross-Registry Dependencies
When a component has dependencies from different registries, the resolver:
- Maintains separate authentication contexts for each registry
- Resolves each dependency from its respective source
- Deduplicates files based on target paths
- Merges configurations (tailwind, cssVars, etc.) from all sources
Best Practices
- Use environment variables for sensitive data like API keys and tokens
- Namespace your registry with a unique, descriptive name
- Document authentication requirements clearly for users
- Implement proper error responses with helpful messages
- Cache registry responses when possible to improve performance
- Support style variants if your components have multiple themes
Troubleshooting
Resources not found
- Verify the registry URL is correct and accessible
- Check that the
{name}placeholder is included in the URL - Ensure the resource exists in the registry
- Confirm the resource type matches what the registry provides
Authentication issues
- Confirm environment variables are set correctly
- Verify API keys/tokens are valid and not expired
- Check that headers are being sent in the correct format
Dependency conflicts
- Review resources with the same name from different registries
- Use fully qualified names (
@namespace/resource) to avoid ambiguity - Check for circular dependencies between registries
- Ensure resource types are compatible when mixing registries
Apps V4 Content Docs Registry Open In V0 (`apps/v4/content/docs/registry/open-in-v0.mdx`)
title: Open in v0
If your registry is hosted and publicly accessible via a URL, you can open a registry item in v0 by using the https://v0.dev/chat/api/open?url=[URL] endpoint.
eg. https://v0.dev/chat/api/open?url=https://ui.shadcn.com/r/styles/new-york/login-01.json
Button
See Build your Open in v0 button for more information on how to build your own Open in v0 button.
Here's a simple example of how to add a Open in v0 button to your site.
import { Button } from "@/components/ui/button"
export function OpenInV0Button({ url }: { url: string }) {
return (
<Button
aria-label="Open in v0"
className="h-8 gap-1 rounded-[6px] bg-black px-3 text-xs text-white hover:bg-black hover:text-white dark:bg-white dark:text-black"
asChild
>
<a
href={`https://v0.dev/chat/api/open?url=${url}`}
target="_blank"
rel="noreferrer"
>
Open in{" "}
<svg
viewBox="0 0 40 20"
fill="none"
xmlns="http://www.w3.org/2000/svg"
className="h-5 w-5 text-current"
>
<path
d="M23.3919 0H32.9188C36.7819 0 39.9136 3.13165 39.9136 6.99475V16.0805H36.0006V6.99475C36.0006 6.90167 35.9969 6.80925 35.9898 6.71766L26.4628 16.079C26.4949 16.08 26.5272 16.0805 26.5595 16.0805H36.0006V19.7762H26.5595C22.6964 19.7762 19.4788 16.6139 19.4788 12.7508V3.68923H23.3919V12.7508C23.3919 12.9253 23.4054 13.0977 23.4316 13.2668L33.1682 3.6995C33.0861 3.6927 33.003 3.68923 32.9188 3.68923H23.3919V0Z"
fill="currentColor"
></path>
<path
d="M13.7688 19.0956L0 3.68759H5.53933L13.6231 12.7337V3.68759H17.7535V17.5746C17.7535 19.6705 15.1654 20.6584 13.7688 19.0956Z"
fill="currentColor"
></path>
</svg>
</a>
</Button>
)
}<OpenInV0Button url="https://example.com/r/hello-world.json" />Authentication
Open in v0 only supports query parameter authentication. It does not support namespaced registries or advanced authentication methods like Bearer tokens or API keys in headers.
Using Query Parameter Authentication
To add authentication to your registry for Open in v0, use a token query parameter:
https://registry.company.com/r/hello-world.json?token=your_secure_token_hereWhen implementing this on your registry server:
- Check for the
tokenquery parameter - Validate the token against your authentication system
- Return a
401 Unauthorizedresponse if the token is invalid or missing - Both the shadcn CLI and Open in v0 will handle the 401 response and display an appropriate message to users
Example Implementation
// Next.js API route example
export async function GET(request: NextRequest) {
const token = request.nextUrl.searchParams.get("token")
if (!isValidToken(token)) {
return NextResponse.json(
{
error: "Unauthorized",
message: "Invalid or missing token",
},
{ status: 401 }
)
}
// Return the registry item
return NextResponse.json(registryItem)
}Apps V4 Content Docs Registry Registry Item Json (`apps/v4/content/docs/registry/registry-item-json.mdx`)
title: registry-item.json
The registry-item.json schema is used to define your custom registry items.
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "hello-world",
"type": "registry:block",
"title": "Hello World",
"description": "A simple hello world component.",
"registryDependencies": [
"button",
"@acme/input-form",
"https://example.com/r/foo"
],
"dependencies": ["[email protected]", "motion"],
"devDependencies": ["tw-animate-css"],
"files": [
{
"path": "registry/new-york/hello-world/hello-world.tsx",
"type": "registry:component"
},
{
"path": "registry/new-york/hello-world/use-hello-world.ts",
"type": "registry:hook"
}
],
"cssVars": {
"theme": {
"font-heading": "Poppins, sans-serif"
},
"light": {
"brand": "oklch(0.205 0.015 18)"
},
"dark": {
"brand": "oklch(0.205 0.015 18)"
}
}
}Definitions
You can see the JSON Schema for registry-item.json here.
$schema
The $schema property is used to specify the schema for the registry-item.json file.
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json"
}name
The name of the item. This is used to identify the item in the registry. It should be unique for your registry.
{
"name": "hello-world"
}title
A human-readable title for your registry item. Keep it short and descriptive.
{
"title": "Hello World"
}description
A description of your registry item. This can be longer and more detailed than the title.
{
"description": "A simple hello world component."
}type
The type property is used to specify the type of your registry item. This is used to determine the type and target path of the item when resolved for a project.
{
"type": "registry:block"
}The following types are supported:
| Type | Description |
|---|---|
registry:base |
Use for entire design systems. |
registry:block |
Use for complex components with multiple files. |
registry:component |
Use for simple components. |
registry:font |
Use for fonts. |
registry:lib |
Use for lib and utils. |
registry:hook |
Use for hooks. |
registry:ui |
Use for UI components and single-file primitives. |
registry:page |
Use for page or file-based routes. |
registry:file |
Use for miscellaneous files. |
registry:style |
Use for registry styles. eg. new-york. |
registry:theme |
Use for themes. |
registry:item |
Use for universal registry items. |
author
The author property is used to specify the author of the registry item.
It can be unique to the registry item or the same as the author of the registry.
{
"author": "John Doe <[email protected]>"
}dependencies
The dependencies property is used to specify the dependencies of your registry item. This is for npm packages.
Use @version to specify the version of your registry item.
{
"dependencies": [
"@radix-ui/react-accordion",
"zod",
"lucide-react",
"[email protected]"
]
}devDependencies
The devDependencies property is used to specify the dev dependencies of your registry item. These are npm packages that are only needed during development.
Use @version to specify the version of the package.
{
"devDependencies": ["tw-animate-css", "[email protected]"]
}registryDependencies
Used for registry dependencies. Can be names, namespaced or URLs.
- For
shadcn/uiregistry items such asbutton,input,select, etc use the name eg.['button', 'input', 'select']. - For namespaced registry items such as
@acmeuse the name eg.['@acme/input-form']. - For custom registry items use the URL of the registry item eg.
['https://example.com/r/hello-world.json'].
{
"registryDependencies": [
"button",
"@acme/input-form",
"https://example.com/r/editor.json"
]
}Note: The CLI will automatically resolve remote registry dependencies.
files
The files property is used to specify the files of your registry item. Each file has a path, type and target (optional) property.
The target property is required for registry:page and registry:file types.
{
"files": [
{
"path": "registry/new-york/hello-world/page.tsx",
"type": "registry:page",
"target": "app/hello/page.tsx"
},
{
"path": "registry/new-york/hello-world/hello-world.tsx",
"type": "registry:component"
},
{
"path": "registry/new-york/hello-world/use-hello-world.ts",
"type": "registry:hook"
},
{
"path": "registry/new-york/hello-world/.env",
"type": "registry:file",
"target": "~/.env"
}
]
}path
The path property is used to specify the path to the file in your registry. This path is used by the build script to parse, transform and build the registry JSON payload.
type
The type property is used to specify the type of the file. See the type section for more information.
target
The target property is used to indicate where the file should be placed in a project. This is optional and only required for registry:page and registry:file types.
By default, the shadcn cli will read a project's components.json file to determine the target path. For some files, such as routes or config you can specify the target path manually.
Use ~ to refer to the root of the project e.g ~/foo.config.js.
tailwind
DEPRECATED: Use cssVars.theme instead for Tailwind v4 projects.
The tailwind property is used for tailwind configuration such as theme, plugins and content.
You can use the tailwind.config property to add colors, animations and plugins to your registry item.
{
"tailwind": {
"config": {
"theme": {
"extend": {
"colors": {
"brand": "hsl(var(--brand))"
},
"keyframes": {
"wiggle": {
"0%, 100%": { "transform": "rotate(-3deg)" },
"50%": { "transform": "rotate(3deg)" }
}
},
"animation": {
"wiggle": "wiggle 1s ease-in-out infinite"
}
}
}
}
}
}cssVars
Use to define CSS variables for your registry item.
{
"cssVars": {
"theme": {
"font-heading": "Poppins, sans-serif"
},
"light": {
"brand": "20 14.3% 4.1%",
"radius": "0.5rem"
},
"dark": {
"brand": "20 14.3% 4.1%"
}
}
}css
Use css to add new rules to the project's CSS file eg. @layer base, @layer components, @utility, @keyframes, @plugin, etc.
{
"css": {
"@plugin @tailwindcss/typography": {},
"@plugin foo": {},
"@layer base": {
"body": {
"font-size": "var(--text-base)",
"line-height": "1.5"
}
},
"@layer components": {
"button": {
"background-color": "var(--color-primary)",
"color": "var(--color-white)"
}
},
"@utility text-magic": {
"font-size": "var(--text-base)",
"line-height": "1.5"
},
"@keyframes wiggle": {
"0%, 100%": {
"transform": "rotate(-3deg)"
},
"50%": {
"transform": "rotate(3deg)"
}
}
}
}envVars
Use envVars to add environment variables to your registry item.
{
"envVars": {
"NEXT_PUBLIC_APP_URL": "http://localhost:4000",
"DATABASE_URL": "postgresql://postgres:postgres@localhost:5432/postgres",
"OPENAI_API_KEY": ""
}
}Environment variables are added to the .env.local or .env file. Existing variables are not overwritten.
IMPORTANT: Use envVars to add development or example variables. Do NOT use it to add production variables.
font
The font property is required for registry:font items. It configures the font family, provider, import name, CSS variable, and the npm package to install for non-Next.js projects.
{
"font": {
"family": "'Inter Variable', sans-serif",
"provider": "google",
"import": "Inter",
"variable": "--font-sans",
"subsets": ["latin"],
"dependency": "@fontsource-variable/inter"
}
}| Property | Type | Required | Description |
|---|---|---|---|
family |
string |
Yes | The CSS font-family value. |
provider |
string |
Yes | The font provider. Currently only google is supported. |
import |
string |
Yes | The import name for the font from next/font/google. |
variable |
string |
Yes | The CSS variable name for the font (e.g., --font-sans, --font-mono). |
weight |
string[] |
No | Array of font weights to include. |
subsets |
string[] |
No | Array of font subsets to include. |
selector |
string |
No | CSS selector to apply the font to. Defaults to html. |
dependency |
string |
No | The npm package to install for non-Next.js projects (e.g., @fontsource-variable/inter). |
docs
Use docs to show custom documentation or message when installing your registry item via the CLI.
{
"docs": "To get an OPENAI_API_KEY, sign up for an account at https://platform.openai.com."
}categories
Use categories to organize your registry item.
{
"categories": ["sidebar", "dashboard"]
}meta
Use meta to add additional metadata to your registry item. You can add any key/value pair that you want to be available to the registry item.
{
"meta": { "foo": "bar" }
}Apps V4 Content Docs Registry Registry Json (`apps/v4/content/docs/registry/registry-json.mdx`)
title: registry.json
The registry.json schema is used to define your custom component registry.
{
"$schema": "https://ui.shadcn.com/schema/registry.json",
"name": "shadcn",
"homepage": "https://ui.shadcn.com",
"items": [
{
"name": "hello-world",
"type": "registry:block",
"title": "Hello World",
"description": "A simple hello world component.",
"registryDependencies": [
"button",
"@acme/input-form",
"https://example.com/r/foo"
],
"dependencies": ["[email protected]", "motion"],
"files": [
{
"path": "registry/new-york/hello-world/hello-world.tsx",
"type": "registry:component"
}
]
}
]
}Definitions
You can see the JSON Schema for registry.json here.
$schema
The $schema property is used to specify the schema for the registry.json file.
{
"$schema": "https://ui.shadcn.com/schema/registry.json"
}name
The name property is used to specify the name of your registry. This is used for data attributes and other metadata.
{
"name": "acme"
}homepage
The homepage of your registry. This is used for data attributes and other metadata.
{
"homepage": "https://acme.com"
}items
The items in your registry. Each item must implement the registry-item schema specification.
{
"items": [
{
"name": "hello-world",
"type": "registry:block",
"title": "Hello World",
"description": "A simple hello world component.",
"registryDependencies": [
"button",
"@acme/input-form",
"https://example.com/r/foo"
],
"dependencies": ["[email protected]", "motion"],
"files": [
{
"path": "registry/new-york/hello-world/hello-world.tsx",
"type": "registry:component"
}
]
}
]
}See the registry-item schema documentation for more information.
Apps V4 Content Docs Rtl Meta.Json (`apps/v4/content/docs/rtl/meta.json`)
{
"title": "RTL",
"pages": ["index", "next", "vite", "start"]
}
Apps V4 Content Docs Rtl Next (`apps/v4/content/docs/rtl/next.mdx`)
title: Next.js
Starting a new project? Use shadcn/create for a fully configured Next.js app with custom themes, Base UI or Radix, and icon libraries.
Create Project
Create a new project using the --rtl flag and the next template.
You can skip this step if you have already created a project using shadcn/create.
npx shadcn@latest create --template next --rtlThis will create a components.json file with the rtl: true flag.
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "base-nova",
"rtl": true
}Add DirectionProvider
Wrap your application with the DirectionProvider component with the direction="rtl" prop.
Then add the dir="rtl" and lang="ar" attributes to the html tag. Update lang="ar" to your target language.
import { DirectionProvider } from "@/components/ui/direction"
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="ar" dir="rtl">
<body>
<DirectionProvider direction="rtl">{children}</DirectionProvider>
</body>
</html>
)
}Add Font
For the best RTL experience, we recommend using fonts that have proper support for your target language. Noto is a great font family for this and it pairs well with Inter and Geist.
import { Noto_Sans_Arabic } from "next/font/google"
import { DirectionProvider } from "@/components/ui/direction"
const fontSans = Noto_Sans_Arabic({
subsets: ["arabic"],
variable: "--font-sans",
})
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="ar" dir="rtl" className={fontSans.variable}>
<body>
<DirectionProvider direction="rtl">{children}</DirectionProvider>
</body>
</html>
)
}For other languages, eg. Hebrew, you can use the Noto_Sans_Hebrew font.
Add Components
You are now ready to add components to your project. The CLI will take care of handling RTL support for you.
npx shadcn@latest add itemApps V4 Content Docs Rtl Start (`apps/v4/content/docs/rtl/start.mdx`)
title: TanStack Start
Starting a new project? Use shadcn/create for a fully configured TanStack Start app with custom themes, Base UI or Radix, and icon libraries.
Create Project
Create a new project using the --rtl flag and the start template.
You can skip this step if you have already created a project using shadcn/create.
npx shadcn@latest create --template start --rtlThis will create a components.json file with the rtl: true flag.
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "base-nova",
"rtl": true
}Add DirectionProvider
Add the dir="rtl" and lang="ar" attributes to the html tag. Update lang="ar" to your target language.
Then wrap your app with the DirectionProvider component with the direction="rtl" prop in your __root.tsx:
import { DirectionProvider } from "@/components/ui/direction"
export const Route = createRootRoute({
component: RootComponent,
})
function RootComponent() {
return (
<html lang="ar" dir="rtl">
<head>
<Meta />
</head>
<body>
<DirectionProvider direction="rtl">{children}</DirectionProvider>
<Scripts />
</body>
</html>
)
}Add Font
For the best RTL experience, we recommend using fonts that have proper support for your target language. Noto is a great font family for this and it pairs well with Inter and Geist.
Install the font using Fontsource:
npm install @fontsource-variable/noto-sans-arabicImport the font in your styles.css:
@import "tailwindcss";
@import "tw-animate-css";
@import "shadcn/tailwind.css";
@import "@fontsource-variable/noto-sans-arabic";
@theme inline {
--font-sans: "Noto Sans Arabic Variable", sans-serif;
}For other languages, eg. Hebrew, you can use @fontsource-variable/noto-sans-hebrew.
Add Components
You are now ready to add components to your project. The CLI will take care of handling RTL support for you.
npx shadcn@latest add itemApps V4 Content Docs Rtl Vite (`apps/v4/content/docs/rtl/vite.mdx`)
title: Vite
Starting a new project? Use shadcn/create for a fully configured Vite app with custom themes, Base UI or Radix, and icon libraries.
Create Project
Create a new project using the --rtl flag and the vite template.
You can skip this step if you have already created a project using shadcn/create.
npx shadcn@latest create --template vite --rtlThis will create a components.json file with the rtl: true flag.
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "base-nova",
"rtl": true
}Add DirectionProvider
Add the dir="rtl" and lang="ar" attributes to the html tag in your index.html. Update lang="ar" to your target language.
<!doctype html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite App</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>Then wrap your app with the DirectionProvider component with the direction="rtl" prop in your main.tsx:
import { StrictMode } from "react"
import { createRoot } from "react-dom/client"
import { DirectionProvider } from "@/components/ui/direction"
import App from "./App"
import "./index.css"
createRoot(document.getElementById("root")!).render(
<StrictMode>
<DirectionProvider direction="rtl">
<App />
</DirectionProvider>
</StrictMode>
)Add Font
For the best RTL experience, we recommend using fonts that have proper support for your target language. Noto is a great font family for this and it pairs well with Inter and Geist.
Install the font using Fontsource:
npm install @fontsource-variable/noto-sans-arabicImport the font in your index.css:
@import "tailwindcss";
@import "tw-animate-css";
@import "shadcn/tailwind.css";
@import "@fontsource-variable/noto-sans-arabic";
@theme inline {
--font-sans: "Noto Sans Arabic Variable", sans-serif;
}For other languages, eg. Hebrew, you can use @fontsource-variable/noto-sans-hebrew.
Add Components
You are now ready to add components to your project. The CLI will take care of handling RTL support for you.
npx shadcn@latest add itemApps V4 Content Docs Components Base Accordion (`apps/v4/content/docs/components/base/accordion.mdx`)
title: Accordion base: base component: true links: doc: https://base-ui.com/react/components/accordion api: https://base-ui.com/react/components/accordion#api-reference
Installation
npx shadcn@latest add accordionnpm install @base-ui/reactUsage
import {
Accordion,
AccordionContent,
AccordionItem,
AccordionTrigger,
} from "@/components/ui/accordion"<Accordion defaultValue={["item-1"]}>
<AccordionItem value="item-1">
<AccordionTrigger>Is it accessible?</AccordionTrigger>
<AccordionContent>
Yes. It adheres to the WAI-ARIA design pattern.
</AccordionContent>
</AccordionItem>
</Accordion>Composition
Use the following composition to build an Accordion:
Accordion
├── AccordionItem
│ ├── AccordionTrigger
│ └── AccordionContent
└── AccordionItem
├── AccordionTrigger
└── AccordionContentExamples
Basic
A basic accordion that shows one item at a time. The first item is open by default.
Multiple
Use the multiple prop to allow multiple items to be open at the same time.
Disabled
Use the disabled prop on AccordionItem to disable individual items.
Borders
Add border to the Accordion and border-b last:border-b-0 to the AccordionItem to add borders to the items.
Card
Wrap the Accordion in a Card component.
RTL
To enable RTL support in shadcn/ui, see the RTL configuration guide.
API Reference
See the Base UI documentation for more information.
Apps V4 Content Docs Components Base Alert Dialog (`apps/v4/content/docs/components/base/alert-dialog.mdx`)
title: Alert Dialog featured: true base: base component: true links: doc: https://base-ui.com/react/components/alert-dialog api: https://base-ui.com/react/components/alert-dialog#api-reference
Installation
npx shadcn@latest add alert-dialognpm install @base-ui/reactUsage
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog"<AlertDialog>
<AlertDialogTrigger render={<Button variant="outline" />}>
Show Dialog
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
<AlertDialogDescription>
This action cannot be undone. This will permanently delete your account
from our servers.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction>Continue</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>Composition
Use the following composition to build an AlertDialog:
AlertDialog
├── AlertDialogTrigger
└── AlertDialogContent
├── AlertDialogHeader
│ ├── AlertDialogMedia
│ ├── AlertDialogTitle
│ └── AlertDialogDescription
└── AlertDialogFooter
├── AlertDialogCancel
└── AlertDialogActionExamples
Basic
A basic alert dialog with a title, description, and cancel and continue buttons.
Small
Use the size="sm" prop to make the alert dialog smaller.
Media
Use the AlertDialogMedia component to add a media element such as an icon or image to the alert dialog.
Small with Media
Use the size="sm" prop to make the alert dialog smaller and the AlertDialogMedia component to add a media element such as an icon or image to the alert dialog.
Destructive
Use the AlertDialogAction component to add a destructive action button to the alert dialog.
RTL
To enable RTL support in shadcn/ui, see the RTL configuration guide.
API Reference
size
Use the size prop on the AlertDialogContent component to control the size of the alert dialog. It accepts the following values:
| Prop | Type | Default |
|---|---|---|
size |
"default" | "sm" |
"default" |
For more information about the other components and their props, see the Base UI documentation.
Apps V4 Content Docs Components Base Alert (`apps/v4/content/docs/components/base/alert.mdx`)
title: Alert base: base component: true
Installation
npx shadcn@latest add alertUsage
import {
Alert,
AlertAction,
AlertDescription,
AlertTitle,
} from "@/components/ui/alert"<Alert>
<InfoIcon />
<AlertTitle>Heads up!</AlertTitle>
<AlertDescription>
You can add components and dependencies to your app using the cli.
</AlertDescription>
<AlertAction>
<Button variant="outline">Enable</Button>
</AlertAction>
</Alert>Composition
Use the following composition to build an Alert:
Alert
├── Icon
├── AlertTitle
├── AlertDescription
└── AlertActionExamples
Basic
A basic alert with an icon, title and description.
Destructive
Use variant="destructive" to create a destructive alert.
Action
Use AlertAction to add a button or other action element to the alert.
Custom Colors
You can customize the alert colors by adding custom classes such as bg-amber-50 dark:bg-amber-950 to the Alert component.
RTL
To enable RTL support in shadcn/ui, see the RTL configuration guide.
API Reference
Alert
The Alert component displays a callout for user attention.
| Prop | Type | Default |
|---|---|---|
variant |
"default" | "destructive" |
"default" |
AlertTitle
The AlertTitle component displays the title of the alert.
| Prop | Type | Default |
|---|---|---|
className |
string |
- |
AlertDescription
The AlertDescription component displays the description or content of the alert.
| Prop | Type | Default |
|---|---|---|
className |
string |
- |
AlertAction
The AlertAction component displays an action element (like a button) positioned absolutely in the top-right corner of the alert.
| Prop | Type | Default |
|---|---|---|
className |
string |
- |
Apps V4 Content Docs Components Base Aspect Ratio (`apps/v4/content/docs/components/base/aspect-ratio.mdx`)
title: Aspect Ratio base: base component: true
Installation
npx shadcn@latest add aspect-rationpm install @base-ui/reactUsage
import { AspectRatio } from "@/components/ui/aspect-ratio"<AspectRatio ratio={16 / 9}>
<Image src="..." alt="Image" className="rounded-md object-cover" />
</AspectRatio>Examples
Square
A square aspect ratio component using the ratio={1 / 1} prop. This is useful for displaying images in a square format.
Portrait
A portrait aspect ratio component using the ratio={9 / 16} prop. This is useful for displaying images in a portrait format.
RTL
To enable RTL support in shadcn/ui, see the RTL configuration guide.
API Reference
AspectRatio
The AspectRatio component displays content within a desired ratio.
| Prop | Type | Default | Required |
|---|---|---|---|
ratio |
number |
- | Yes |
className |
string |
- | No |
For more information, see the Base UI documentation.
Apps V4 Content Docs Components Base Avatar (`apps/v4/content/docs/components/base/avatar.mdx`)
title: Avatar base: base component: true links: doc: https://base-ui.com/react/components/avatar api: https://base-ui.com/react/components/avatar#api-reference
Installation
npx shadcn@latest add avatarnpm install @base-ui/reactUsage
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"<Avatar>
<AvatarImage src="https://github.com/shadcn.png" />
<AvatarFallback>CN</AvatarFallback>
</Avatar>Composition
Use the following composition to build an Avatar:
Avatar
├── AvatarImage
├── AvatarFallback
└── AvatarBadgeUse the following composition to build an AvatarGroup:
AvatarGroup
├── Avatar
│ ├── AvatarImage
│ ├── AvatarFallback
│ └── AvatarBadge
├── Avatar
│ ├── AvatarImage
│ ├── AvatarFallback
│ └── AvatarBadge
└── AvatarGroupCountExamples
Basic
A basic avatar component with an image and a fallback.
Badge
Use the AvatarBadge component to add a badge to the avatar. The badge is positioned at the bottom right of the avatar.
Use the className prop to add custom styles to the badge such as custom colors, sizes, etc.
<Avatar>
<AvatarImage src="https://github.com/shadcn.png" alt="@shadcn" />
<AvatarFallback>CN</AvatarFallback>
<AvatarBadge className="bg-green-600 dark:bg-green-800" />
</Avatar>Badge with Icon
You can also use an icon inside <AvatarBadge>.
Avatar Group
Use the AvatarGroup component to add a group of avatars.
Avatar Group Count
Use <AvatarGroupCount> to add a count to the group.
Avatar Group with Icon
You can also use an icon inside <AvatarGroupCount>.
Sizes
Use the size prop to change the size of the avatar.
Dropdown
You can use the Avatar component as a trigger for a dropdown menu.
RTL
To enable RTL support in shadcn/ui, see the RTL configuration guide.
API Reference
Avatar
The Avatar component is the root component that wraps the avatar image and fallback.
| Prop | Type | Default |
|---|---|---|
size |
"default" | "sm" | "lg" |
"default" |
className |
string |
- |
AvatarImage
The AvatarImage component displays the avatar image. It accepts all Base UI Avatar Image props.
| Prop | Type | Default |
|---|---|---|
src |
string |
- |
alt |
string |
- |
className |
string |
- |
AvatarFallback
The AvatarFallback component displays a fallback when the image fails to load. It accepts all Base UI Avatar Fallback props.
| Prop | Type | Default |
|---|---|---|
className |
string |
- |
AvatarBadge
The AvatarBadge component displays a badge indicator on the avatar, typically positioned at the bottom right.
| Prop | Type | Default |
|---|---|---|
className |
string |
- |
AvatarGroup
The AvatarGroup component displays a group of avatars with overlapping styling.
| Prop | Type | Default |
|---|---|---|
className |
string |
- |
AvatarGroupCount
The AvatarGroupCount component displays a count indicator in an avatar group, typically showing the number of additional avatars.
| Prop | Type | Default |
|---|---|---|
className |
string |
- |
For more information about Base UI Avatar props, see the Base UI documentation.
Apps V4 Content Docs Components Base Badge (`apps/v4/content/docs/components/base/badge.mdx`)
title: Badge base: base component: true
Installation
npx shadcn@latest add badgeUsage
import { Badge } from "@/components/ui/badge"<Badge variant="default | outline | secondary | destructive">Badge</Badge>Examples
Variants
Use the variant prop to change the variant of the badge.
With Icon
You can render an icon inside the badge. Use data-icon="inline-start" to render the icon on the left and data-icon="inline-end" to render the icon on the right.
With Spinner
You can render a spinner inside the badge. Remember to add the data-icon="inline-start" or data-icon="inline-end" prop to the spinner.
Link
Use the render prop to render a link as a badge.
Custom Colors
You can customize the colors of a badge by adding custom classes such as bg-green-50 dark:bg-green-800 to the Badge component.
RTL
To enable RTL support in shadcn/ui, see the RTL configuration guide.
API Reference
Badge
The Badge component displays a badge or a component that looks like a badge.
| Prop | Type | Default |
|---|---|---|
variant |
"default" | "secondary" | "destructive" | "outline" | "ghost" | "link" |
"default" |
className |
string |
- |
Apps V4 Content Docs Components Base Breadcrumb (`apps/v4/content/docs/components/base/breadcrumb.mdx`)
title: Breadcrumb base: base component: true
Installation
npx shadcn@latest add breadcrumbUsage
import {
Breadcrumb,
BreadcrumbItem,
BreadcrumbLink,
BreadcrumbList,
BreadcrumbPage,
BreadcrumbSeparator,
} from "@/components/ui/breadcrumb"<Breadcrumb>
<BreadcrumbList>
<BreadcrumbItem>
<BreadcrumbLink render={<a href="/" />}>Home</BreadcrumbLink>
</BreadcrumbItem>
<BreadcrumbSeparator />
<BreadcrumbItem>
<BreadcrumbLink render={<a href="/components" />}>
Components
</BreadcrumbLink>
</BreadcrumbItem>
<BreadcrumbSeparator />
<BreadcrumbItem>
<BreadcrumbPage>Breadcrumb</BreadcrumbPage>
</BreadcrumbItem>
</BreadcrumbList>
</Breadcrumb>Composition
Use the following composition to build a Breadcrumb:
Breadcrumb
└── BreadcrumbList
├── BreadcrumbItem
│ └── BreadcrumbLink
├── BreadcrumbSeparator
├── BreadcrumbItem
│ └── BreadcrumbLink
├── BreadcrumbSeparator
└── BreadcrumbItem
└── BreadcrumbPageExamples
Basic
A basic breadcrumb with a home link and a components link.
Custom separator
Use a custom component as children for `` to create a custom separator.
Dropdown
You can compose `` with a <DropdownMenu /> to create a dropdown in the breadcrumb.
Collapsed
We provide a `` component to show a collapsed state when the breadcrumb is too long.
Link component
To use a custom link component from your routing library, you can use the render prop on ``.
RTL
To enable RTL support in shadcn/ui, see the RTL configuration guide.
API Reference
Breadcrumb
The Breadcrumb component is the root navigation element that wraps all breadcrumb components.
| Prop | Type | Default |
|---|---|---|
className |
string |
- |
BreadcrumbList
The BreadcrumbList component displays the ordered list of breadcrumb items.
| Prop | Type | Default |
|---|---|---|
className |
string |
- |
BreadcrumbItem
The BreadcrumbItem component wraps individual breadcrumb items.
| Prop | Type | Default |
|---|---|---|
className |
string |
- |
BreadcrumbLink
The BreadcrumbLink component displays a clickable link in the breadcrumb.
| Prop | Type | Default |
|---|---|---|
className |
string |
- |
BreadcrumbPage
The BreadcrumbPage component displays the current page in the breadcrumb (non-clickable).
| Prop | Type | Default |
|---|---|---|
className |
string |
- |
BreadcrumbSeparator
The BreadcrumbSeparator component displays a separator between breadcrumb items. You can pass custom children to override the default separator icon.
| Prop | Type | Default |
|---|---|---|
children |
React.ReactNode |
- |
className |
string |
- |
BreadcrumbEllipsis
The BreadcrumbEllipsis component displays an ellipsis indicator for collapsed breadcrumb items.
| Prop | Type | Default |
|---|---|---|
className |
string |
- |
Apps V4 Content Docs Components Base Button Group (`apps/v4/content/docs/components/base/button-group.mdx`)
title: Button Group base: base component: true
Installation
npx shadcn@latest add button-groupnpm install @base-ui/reactUsage
import {
ButtonGroup,
ButtonGroupSeparator,
ButtonGroupText,
} from "@/components/ui/button-group"<ButtonGroup>
<Button>Button 1</Button>
<Button>Button 2</Button>
</ButtonGroup>Composition
Use the following composition to build a ButtonGroup:
ButtonGroup
├── Button or Input
├── ButtonGroupSeparator
└── ButtonGroupTextAccessibility
- The
ButtonGroupcomponent has theroleattribute set togroup. - Use Tab to navigate between the buttons in the group.
- Use
aria-labeloraria-labelledbyto label the button group.
<ButtonGroup aria-label="Button group">
<Button>Button 1</Button>
<Button>Button 2</Button>
</ButtonGroup>ButtonGroup vs ToggleGroup
- Use the
ButtonGroupcomponent when you want to group buttons that perform an action. - Use the
ToggleGroupcomponent when you want to group buttons that toggle a state.
Examples
Orientation
Set the orientation prop to change the button group layout.
Size
Control the size of buttons using the size prop on individual buttons.
Nested
Nest `` components to create button groups with spacing.
Separator
The ButtonGroupSeparator component visually divides buttons within a group.
Buttons with variant outline do not need a separator since they have a border. For other variants, a separator is recommended to improve the visual hierarchy.
Split
Create a split button group by adding two buttons separated by a ButtonGroupSeparator.
Input
Wrap an Input component with buttons.
Input Group
Wrap an InputGroup component to create complex input layouts.
Dropdown Menu
Create a split button group with a DropdownMenu component.
Select
Pair with a Select component.
Popover
Use with a Popover component.
RTL
To enable RTL support in shadcn/ui, see the RTL configuration guide.
API Reference
ButtonGroup
The ButtonGroup component is a container that groups related buttons together with consistent styling.
| Prop | Type | Default |
|---|---|---|
orientation |
"horizontal" | "vertical" |
"horizontal" |
<ButtonGroup>
<Button>Button 1</Button>
<Button>Button 2</Button>
</ButtonGroup>Nest multiple button groups to create complex layouts with spacing. See the nested example for more details.
<ButtonGroup>
<ButtonGroup />
<ButtonGroup />
</ButtonGroup>ButtonGroupSeparator
The ButtonGroupSeparator component visually divides buttons within a group.
| Prop | Type | Default |
|---|---|---|
orientation |
"horizontal" | "vertical" |
"vertical" |
<ButtonGroup>
<Button>Button 1</Button>
<ButtonGroupSeparator />
<Button>Button 2</Button>
</ButtonGroup>ButtonGroupText
Use this component to display text within a button group.
| Prop | Type | Default |
|---|---|---|
asChild |
boolean |
false |
<ButtonGroup>
<ButtonGroupText>Text</ButtonGroupText>
<Button>Button</Button>
</ButtonGroup>Use the asChild prop to render a custom component as the text, for example a label.
import { ButtonGroupText } from "@/components/ui/button-group"
import { Label } from "@/components/ui/label"
export function ButtonGroupTextDemo() {
return (
<ButtonGroup>
<ButtonGroupText asChild>
<Label htmlFor="name">Text</Label>
</ButtonGroupText>
<Input placeholder="Type something here..." id="name" />
</ButtonGroup>
)
}Apps V4 Content Docs Components Base Button (`apps/v4/content/docs/components/base/button.mdx`)
title: Button featured: true base: base component: true
Installation
npx shadcn@latest add buttonnpm install @base-ui/reactUsage
import { Button } from "@/components/ui/button"<Button variant="outline">Button</Button>Cursor
Tailwind v4 switched from cursor: pointer to cursor: default for the button component.
If you want to keep the cursor: pointer behavior, add the following code to your CSS file:
@layer base {
button:not(:disabled),
[role="button"]:not(:disabled) {
cursor: pointer;
}
}Examples
Size
Use the size prop to change the size of the button.
Default
Outline
Secondary
Ghost
Destructive
Link
Icon
With Icon
Remember to add the data-icon="inline-start" or data-icon="inline-end" attribute to the icon for the correct spacing.
Rounded
Use the rounded-full class to make the button rounded.
Spinner
Render a <Spinner /> component inside the button to show a loading state. Remember to add the data-icon="inline-start" or data-icon="inline-end" attribute to the spinner for the correct spacing.
Button Group
To create a button group, use the ButtonGroup component. See the Button Group documentation for more details.
As Link
You can use the buttonVariants helper to make a link look like a button.
Do not use } nativeButton={false} /> for links. The Base UI Button component always applies role="button", which overrides the semantic link role on <a> elements. Use buttonVariants with a plain <a> tag instead.
RTL
To enable RTL support in shadcn/ui, see the RTL configuration guide.
API Reference
Button
The Button component is a wrapper around the button element that adds a variety of styles and functionality.
| Prop | Type | Default |
|---|---|---|
variant |
"default" | "outline" | "ghost" | "destructive" | "secondary" | "link" |
"default" |
size |
"default" | "xs" | "sm" | "lg" | "icon" | "icon-xs" | "icon-sm" | "icon-lg" |
"default" |
Apps V4 Content Docs Components Base Calendar (`apps/v4/content/docs/components/base/calendar.mdx`)
title: Calendar base: base component: true links: doc: https://react-day-picker.js.org
Installation
npx shadcn@latest add calendarnpm install react-day-picker date-fnsButton component to your project.
The Calendar component uses the Button component. Make sure you have it installed in your project.
Usage
import { Calendar } from "@/components/ui/calendar"const [date, setDate] = React.useState<Date | undefined>(new Date())
return (
<Calendar
mode="single"
selected={date}
onSelect={setDate}
className="rounded-lg border"
/>
)See the React DayPicker documentation for more information.
About
The Calendar component is built on top of React DayPicker.
Date Picker
You can use the <Calendar> component to build a date picker. See the Date Picker page for more information.
Persian / Hijri / Jalali Calendar
To use the Persian calendar, edit components/ui/calendar.tsx and replace react-day-picker with react-day-picker/persian.
- import { DayPicker } from "react-day-picker"
+ import { DayPicker } from "react-day-picker/persian"Selected Date (With TimeZone)
The Calendar component accepts a timeZone prop to ensure dates are displayed and selected in the user's local timezone.
export function CalendarWithTimezone() {
const [date, setDate] = React.useState<Date | undefined>(undefined)
const [timeZone, setTimeZone] = React.useState<string | undefined>(undefined)
React.useEffect(() => {
setTimeZone(Intl.DateTimeFormat().resolvedOptions().timeZone)
}, [])
return (
<Calendar
mode="single"
selected={date}
onSelect={setDate}
timeZone={timeZone}
/>
)
}Note: If you notice a selected date offset (for example, selecting the 20th highlights the 19th), make sure the timeZone prop is set to the user's local timezone.
Why client-side? The timezone is detected using Intl.DateTimeFormat().resolvedOptions().timeZone inside a useEffect to ensure compatibility with server-side rendering. Detecting the timezone during render would cause hydration mismatches, as the server and client may be in different timezones.
Examples
Basic
A basic calendar component. We used className="rounded-lg border" to style the calendar.
Range Calendar
Use the mode="range" prop to enable range selection.
Month and Year Selector
Use captionLayout="dropdown" to show month and year dropdowns.
Presets
Date and Time Picker
Booked dates
Custom Cell Size
You can customize the size of calendar cells using the --cell-size CSS variable. You can also make it responsive by using breakpoint-specific values:
<Calendar
mode="single"
selected={date}
onSelect={setDate}
className="rounded-lg border [--cell-size:--spacing(11)] md:[--cell-size:--spacing(12)]"
/>Or use fixed values:
<Calendar
mode="single"
selected={date}
onSelect={setDate}
className="rounded-lg border [--cell-size:2.75rem] md:[--cell-size:3rem]"
/>Week Numbers
Use showWeekNumber to show week numbers.
RTL
To enable RTL support in shadcn/ui, see the RTL configuration guide.
See also the Hijri Guide for enabling the Persian / Hijri / Jalali calendar.
When using RTL, import the locale from react-day-picker/locale and pass both the locale and dir props to the Calendar component:
import { arSA } from "react-day-picker/locale"
;<Calendar
mode="single"
selected={date}
onSelect={setDate}
locale={arSA}
dir="rtl"
/>API Reference
See the React DayPicker documentation for more information on the Calendar component.
Changelog
RTL Support
If you're upgrading from a previous version of the Calendar component, you'll need to apply the following updates to add locale support:
Locale type.
Add Locale to your imports from react-day-picker:
import {
DayPicker,
getDefaultClassNames,
type DayButton,
+ type Locale,
} from "react-day-picker"locale prop to the Calendar component.
Add the locale prop to the component's props:
function Calendar({
className,
classNames,
showOutsideDays = true,
captionLayout = "label",
buttonVariant = "ghost",
+ locale,
formatters,
components,
...props
}: React.ComponentProps<typeof DayPicker> & {
buttonVariant?: React.ComponentProps<typeof Button>["variant"]
}) {locale to DayPicker.
Pass the locale prop to the DayPicker component:
<DayPicker
showOutsideDays={showOutsideDays}
className={cn(...)}
captionLayout={captionLayout}
+ locale={locale}
formatters={{
formatMonthDropdown: (date) =>
- date.toLocaleString("default", { month: "short" }),
+ date.toLocaleString(locale?.code, { month: "short" }),
...formatters,
}}Update the CalendarDayButton component signature and pass locale:
function CalendarDayButton({
className,
day,
modifiers,
+ locale,
...props
- }: React.ComponentProps<typeof DayButton>) {
+ }: React.ComponentProps<typeof DayButton> & { locale?: Partial<Locale> }) {Use locale?.code in the date formatting:
<Button
variant="ghost"
size="icon"
- data-day={day.date.toLocaleDateString()}
+ data-day={day.date.toLocaleDateString(locale?.code)}
...
/>Update the DayButton component usage to pass the locale prop:
components={{
...
- DayButton: CalendarDayButton,
+ DayButton: ({ ...props }) => (
+ <CalendarDayButton locale={locale} {...props} />
+ ),
...
}}Replace directional classes with logical properties for better RTL support:
// In the day classNames:
- [&:last-child[data-selected=true]_button]:rounded-r-(--cell-radius)
+ [&:last-child[data-selected=true]_button]:rounded-e-(--cell-radius)
- [&:nth-child(2)[data-selected=true]_button]:rounded-l-(--cell-radius)
+ [&:nth-child(2)[data-selected=true]_button]:rounded-s-(--cell-radius)
- [&:first-child[data-selected=true]_button]:rounded-l-(--cell-radius)
+ [&:first-child[data-selected=true]_button]:rounded-s-(--cell-radius)
// In range_start classNames:
- rounded-l-(--cell-radius) ... after:right-0
+ rounded-s-(--cell-radius) ... after:end-0
// In range_end classNames:
- rounded-r-(--cell-radius) ... after:left-0
+ rounded-e-(--cell-radius) ... after:start-0
// In CalendarDayButton className:
- data-[range-end=true]:rounded-r-(--cell-radius)
+ data-[range-end=true]:rounded-e-(--cell-radius)
- data-[range-start=true]:rounded-l-(--cell-radius)
+ data-[range-start=true]:rounded-s-(--cell-radius)After applying these changes, you can use the locale prop to provide locale-specific formatting:
import { enUS } from "react-day-picker/locale"
;<Calendar mode="single" selected={date} onSelect={setDate} locale={enUS} />Apps V4 Content Docs Components Base Card (`apps/v4/content/docs/components/base/card.mdx`)
title: Card base: base component: true
Installation
npx shadcn@latest add cardUsage
import {
Card,
CardAction,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@/components/ui/card"<Card>
<CardHeader>
<CardTitle>Card Title</CardTitle>
<CardDescription>Card Description</CardDescription>
<CardAction>Card Action</CardAction>
</CardHeader>
<CardContent>
<p>Card Content</p>
</CardContent>
<CardFooter>
<p>Card Footer</p>
</CardFooter>
</Card>Composition
Use the following composition to build a Card:
Card
├── CardHeader
│ ├── CardTitle
│ ├── CardDescription
│ └── CardAction
├── CardContent
└── CardFooterExamples
Size
Use the size="sm" prop to set the size of the card to small. The small size variant uses smaller spacing.
Image
Add an image before the card header to create a card with an image.
RTL
To enable RTL support in shadcn/ui, see the RTL configuration guide.
API Reference
Card
The Card component is the root container for card content.
| Prop | Type | Default |
|---|---|---|
size |
"default" | "sm" |
"default" |
className |
string |
- |
CardHeader
The CardHeader component is used for a title, description, and optional action.
| Prop | Type | Default |
|---|---|---|
className |
string |
- |
CardTitle
The CardTitle component is used for the card title.
| Prop | Type | Default |
|---|---|---|
className |
string |
- |
CardDescription
The CardDescription component is used for helper text under the title.
| Prop | Type | Default |
|---|---|---|
className |
string |
- |
CardAction
The CardAction component places content in the top-right of the header (for example, a button or a badge).
| Prop | Type | Default |
|---|---|---|
className |
string |
- |
CardContent
The CardContent component is used for the main card body.
| Prop | Type | Default |
|---|---|---|
className |
string |
- |
CardFooter
The CardFooter component is used for actions and secondary content at the bottom of the card.
| Prop | Type | Default |
|---|---|---|
className |
string |
- |
Apps V4 Content Docs Components Base Carousel (`apps/v4/content/docs/components/base/carousel.mdx`)
title: Carousel base: base component: true links: doc: https://www.embla-carousel.com/get-started/react api: https://www.embla-carousel.com/api
About
The carousel component is built using the Embla Carousel library.
Installation
npx shadcn@latest add carouselnpm install embla-carousel-reactUsage
import {
Carousel,
CarouselContent,
CarouselItem,
CarouselNext,
CarouselPrevious,
} from "@/components/ui/carousel"<Carousel>
<CarouselContent>
<CarouselItem>...</CarouselItem>
<CarouselItem>...</CarouselItem>
<CarouselItem>...</CarouselItem>
</CarouselContent>
<CarouselPrevious />
<CarouselNext />
</Carousel>Composition
Use the following composition to build a Carousel:
Carousel
├── CarouselContent
│ ├── CarouselItem
│ └── CarouselItem
├── CarouselPrevious
└── CarouselNextExamples
Sizes
To set the size of the items, you can use the basis utility class on the <CarouselItem />.
// 33% of the carousel width.
<Carousel>
<CarouselContent>
<CarouselItem className="basis-1/3">...</CarouselItem>
<CarouselItem className="basis-1/3">...</CarouselItem>
<CarouselItem className="basis-1/3">...</CarouselItem>
</CarouselContent>
</Carousel>// 50% on small screens and 33% on larger screens.
<Carousel>
<CarouselContent>
<CarouselItem className="md:basis-1/2 lg:basis-1/3">...</CarouselItem>
<CarouselItem className="md:basis-1/2 lg:basis-1/3">...</CarouselItem>
<CarouselItem className="md:basis-1/2 lg:basis-1/3">...</CarouselItem>
</CarouselContent>
</Carousel>Spacing
To set the spacing between the items, we use a pl-[VALUE] utility on the <CarouselItem /> and a negative -ml-[VALUE] on the <CarouselContent />.
<Carousel>
<CarouselContent className="-ml-4">
<CarouselItem className="pl-4">...</CarouselItem>
<CarouselItem className="pl-4">...</CarouselItem>
<CarouselItem className="pl-4">...</CarouselItem>
</CarouselContent>
</Carousel><Carousel>
<CarouselContent className="-ml-2 md:-ml-4">
<CarouselItem className="pl-2 md:pl-4">...</CarouselItem>
<CarouselItem className="pl-2 md:pl-4">...</CarouselItem>
<CarouselItem className="pl-2 md:pl-4">...</CarouselItem>
</CarouselContent>
</Carousel>Orientation
Use the orientation prop to set the orientation of the carousel.
<Carousel orientation="vertical | horizontal">
<CarouselContent>
<CarouselItem>...</CarouselItem>
<CarouselItem>...</CarouselItem>
<CarouselItem>...</CarouselItem>
</CarouselContent>
</Carousel>Options
You can pass options to the carousel using the opts prop. See the Embla Carousel docs for more information.
<Carousel
opts={{
align: "start",
loop: true,
}}
>
<CarouselContent>
<CarouselItem>...</CarouselItem>
<CarouselItem>...</CarouselItem>
<CarouselItem>...</CarouselItem>
</CarouselContent>
</Carousel>API
Use a state and the setApi prop to get an instance of the carousel API.
import { type CarouselApi } from "@/components/ui/carousel"
export function Example() {
const [api, setApi] = React.useState<CarouselApi>()
const [current, setCurrent] = React.useState(0)
const [count, setCount] = React.useState(0)
React.useEffect(() => {
if (!api) {
return
}
setCount(api.scrollSnapList().length)
setCurrent(api.selectedScrollSnap() + 1)
api.on("select", () => {
setCurrent(api.selectedScrollSnap() + 1)
})
}, [api])
return (
<Carousel setApi={setApi}>
<CarouselContent>
<CarouselItem>...</CarouselItem>
<CarouselItem>...</CarouselItem>
<CarouselItem>...</CarouselItem>
</CarouselContent>
</Carousel>
)
}Events
You can listen to events using the api instance from setApi.
import { type CarouselApi } from "@/components/ui/carousel"
export function Example() {
const [api, setApi] = React.useState<CarouselApi>()
React.useEffect(() => {
if (!api) {
return
}
api.on("select", () => {
// Do something on select.
})
}, [api])
return (
<Carousel setApi={setApi}>
<CarouselContent>
<CarouselItem>...</CarouselItem>
<CarouselItem>...</CarouselItem>
<CarouselItem>...</CarouselItem>
</CarouselContent>
</Carousel>
)
}See the Embla Carousel docs for more information on using events.
Plugins
You can use the plugins prop to add plugins to the carousel.
import Autoplay from "embla-carousel-autoplay"
export function Example() {
return (
<Carousel
plugins={[
Autoplay({
delay: 2000,
}),
]}
>
// ...
</Carousel>
)
}RTL
To enable RTL support in shadcn/ui, see the RTL configuration guide.
When localizing the carousel for RTL languages, you need to set the direction option in the opts prop to match the text direction. This ensures the carousel scrolls in the correct direction.
<Carousel
dir={dir}
opts={{
direction: dir,
}}
>
<CarouselContent>
<CarouselItem>...</CarouselItem>
<CarouselItem>...</CarouselItem>
<CarouselItem>...</CarouselItem>
</CarouselContent>
<CarouselPrevious className="rtl:rotate-180" />
<CarouselNext className="rtl:rotate-180" />
</Carousel>The direction option accepts "ltr" or "rtl" and should match the dir prop value. You may also want to rotate the navigation buttons using the rtl:rotate-180 class to ensure they point in the correct direction.
API Reference
See the Embla Carousel docs for more information on props and plugins.
Apps V4 Content Docs Components Base Chart (`apps/v4/content/docs/components/base/chart.mdx`)
title: Chart base: base component: true
Updated: The chart component now uses Recharts v3. If you're upgrading existing chart code, see Updating to Recharts v3.
Introducing Charts. A collection of chart components that you can copy and paste into your apps.
Charts are designed to look great out of the box. They work well with the other components and are fully customizable to fit your project.
Component
We use Recharts under the hood.
We designed the chart component with composition in mind. You build your charts using Recharts components and only bring in custom components, such as ChartTooltip, when and where you need it.
import { Bar, BarChart } from "recharts"
import { ChartContainer, ChartTooltipContent } from "@/components/ui/chart"
export function MyChart() {
return (
<ChartContainer>
<BarChart data={data}>
<Bar dataKey="value" />
<ChartTooltip content={<ChartTooltipContent />} />
</BarChart>
</ChartContainer>
)
}We do not wrap Recharts. This means you're not locked into an abstraction. When a new Recharts version is released, you can follow the official upgrade path to upgrade your charts.
The components are yours.
Updating to Recharts v3
If you're updating older chart code to Recharts v3:
- Use
var(--chart-1)instead ofhsl(var(--chart-1))when you reference chart tokens from your CSS variables. - Use
ChartTooltip.defaultIndexfor initial tooltip state only. Keep persistent active shapes in your own chart state. - Remove
layoutfromwhen the parentalready defines it. - Keep a height,
min-h-*, oraspect-*onChartContainersoResponsiveContainercan measure on first render.
Installation
npx shadcn@latest add chartnpm install rechartscomponents/ui/chart.tsx.
@layer base {
:root {
--chart-1: oklch(0.646 0.222 41.116);
--chart-2: oklch(0.6 0.118 184.704);
--chart-3: oklch(0.398 0.07 227.392);
--chart-4: oklch(0.828 0.189 84.429);
--chart-5: oklch(0.769 0.188 70.08);
}
.dark {
--chart-1: oklch(0.488 0.243 264.376);
--chart-2: oklch(0.696 0.17 162.48);
--chart-3: oklch(0.769 0.188 70.08);
--chart-4: oklch(0.627 0.265 303.9);
--chart-5: oklch(0.645 0.246 16.439);
}
}Your First Chart
Let's build your first chart. We'll build a bar chart, add a grid, axis, tooltip and legend.
The following data represents the number of desktop and mobile users for each month.
Note: Your data can be in any shape. You are not limited to the shape of the data below. Use the dataKey prop to map your data to the chart.
const chartData = [
{ month: "January", desktop: 186, mobile: 80 },
{ month: "February", desktop: 305, mobile: 200 },
{ month: "March", desktop: 237, mobile: 120 },
{ month: "April", desktop: 73, mobile: 190 },
{ month: "May", desktop: 209, mobile: 130 },
{ month: "June", desktop: 214, mobile: 140 },
]The chart config holds configuration for the chart. This is where you place human-readable strings, such as labels, icons and color tokens for theming.
import { type ChartConfig } from "@/components/ui/chart"
const chartConfig = {
desktop: {
label: "Desktop",
color: "#2563eb",
},
mobile: {
label: "Mobile",
color: "#60a5fa",
},
} satisfies ChartConfigYou can now build your chart using Recharts components.
Important: Remember to set a min-h-[VALUE] on the ChartContainer component. This is required for the chart to be responsive.
Add a Grid
Let's add a grid to the chart.
CartesianGrid component.
import { Bar, BarChart, CartesianGrid } from "recharts"CartesianGrid component to your chart.
<ChartContainer config={chartConfig} className="min-h-[200px] w-full">
<BarChart accessibilityLayer data={chartData}>
<CartesianGrid vertical={false} />
<Bar dataKey="desktop" fill="var(--color-desktop)" radius={4} />
<Bar dataKey="mobile" fill="var(--color-mobile)" radius={4} />
</BarChart>
</ChartContainer>Add an Axis
To add an x-axis to the chart, we'll use the XAxis component.
XAxis component.
import { Bar, BarChart, CartesianGrid, XAxis } from "recharts"XAxis component to your chart.
<ChartContainer config={chartConfig} className="h-[200px] w-full">
<BarChart accessibilityLayer data={chartData}>
<CartesianGrid vertical={false} />
<XAxis
dataKey="month"
tickLine={false}
tickMargin={10}
axisLine={false}
tickFormatter={(value) => value.slice(0, 3)}
/>
<Bar dataKey="desktop" fill="var(--color-desktop)" radius={4} />
<Bar dataKey="mobile" fill="var(--color-mobile)" radius={4} />
</BarChart>
</ChartContainer>Add Tooltip
So far we've only used components from Recharts. They look great out of the box thanks to some customization in the chart component.
To add a tooltip, we'll use the custom ChartTooltip and ChartTooltipContent components from chart.
ChartTooltip and ChartTooltipContent components.
import { ChartTooltip, ChartTooltipContent } from "@/components/ui/chart"<ChartContainer config={chartConfig} className="h-[200px] w-full">
<BarChart accessibilityLayer data={chartData}>
<CartesianGrid vertical={false} />
<XAxis
dataKey="month"
tickLine={false}
tickMargin={10}
axisLine={false}
tickFormatter={(value) => value.slice(0, 3)}
/>
<ChartTooltip content={<ChartTooltipContent />} />
<Bar dataKey="desktop" fill="var(--color-desktop)" radius={4} />
<Bar dataKey="mobile" fill="var(--color-mobile)" radius={4} />
</BarChart>
</ChartContainer>Hover to see the tooltips. Easy, right? Two components, and we've got a beautiful tooltip.
Add Legend
We'll do the same for the legend. We'll use the ChartLegend and ChartLegendContent components from chart.
ChartLegend and ChartLegendContent components.
import { ChartLegend, ChartLegendContent } from "@/components/ui/chart"<ChartContainer config={chartConfig} className="h-[200px] w-full">
<BarChart accessibilityLayer data={chartData}>
<CartesianGrid vertical={false} />
<XAxis
dataKey="month"
tickLine={false}
tickMargin={10}
axisLine={false}
tickFormatter={(value) => value.slice(0, 3)}
/>
<ChartTooltip content={<ChartTooltipContent />} />
<ChartLegend content={<ChartLegendContent />} />
<Bar dataKey="desktop" fill="var(--color-desktop)" radius={4} />
<Bar dataKey="mobile" fill="var(--color-mobile)" radius={4} />
</BarChart>
</ChartContainer>Done. You've built your first chart! What's next?
Chart Config
The chart config is where you define the labels, icons and colors for a chart.
It is intentionally decoupled from chart data.
This allows you to share config and color tokens between charts. It can also work independently for cases where your data or color tokens live remotely or in a different format.
import { Monitor } from "lucide-react"
import { type ChartConfig } from "@/components/ui/chart"
const chartConfig = {
desktop: {
label: "Desktop",
icon: Monitor,
// A color like 'hsl(220, 98%, 61%)' or 'var(--color-name)'
color: "#2563eb",
// OR a theme object with 'light' and 'dark' keys
theme: {
light: "#2563eb",
dark: "#dc2626",
},
},
} satisfies ChartConfigTheming
Charts have built-in support for theming. You can use css variables (recommended) or color values in any color format, such as hex, hsl or oklch.
CSS Variables
@layer base {
:root {
--chart-1: oklch(0.646 0.222 41.116);
--chart-2: oklch(0.6 0.118 184.704);
}
.dark {
--chart-1: oklch(0.488 0.243 264.376);
--chart-2: oklch(0.696 0.17 162.48);
}
}chartConfig
const chartConfig = {
desktop: {
label: "Desktop",
color: "var(--chart-1)",
},
mobile: {
label: "Mobile",
color: "var(--chart-2)",
},
} satisfies ChartConfighex, hsl or oklch
You can also define your colors directly in the chart config. Use the color format you prefer.
const chartConfig = {
desktop: {
label: "Desktop",
color: "#2563eb",
},
mobile: {
label: "Mobile",
color: "hsl(220, 98%, 61%)",
},
tablet: {
label: "Tablet",
color: "oklch(0.5 0.2 240)",
},
laptop: {
label: "Laptop",
color: "var(--chart-2)",
},
} satisfies ChartConfigUsing Colors
To use the theme colors in your chart, reference the colors using the format var(--color-KEY).
Components
<Bar dataKey="desktop" fill="var(--color-desktop)" />Chart Data
cons