Sub topic 5
How shadcn/ui works: copy, own, and modify
This chapter assumes you know React function components and props, basic TypeScript, and Tailwind utility classes. It also assumes you have met the idea of headless components and Radix UI primitives from the earlier chapters. Here you will see how shadcn/ui is structured, what it puts in your repository, and what that means for your workflow. The CLI commands get a full treatment in the next chapter.
Not a component library in the usual sense
Most component libraries are npm dependencies. You install a package, import Button from it, and customize it through props, theme objects, or CSS overrides. The component's source lives in node_modules, and you cannot edit it without patching or forking.
shadcn/ui works differently. It is a collection of component source files plus a CLI that copies them into your project. After you run the copy, the files are yours. There is no shadcn-ui package in your dependencies that supplies Button.
| Aspect | Conventional library | shadcn/ui |
|---|---|---|
| Where the source lives | `node_modules` | Your repository, usually `components/ui` |
| How you change appearance | Props, theme config, CSS overrides | Edit the file directly |
| Updates | Bump the package version | Re-run the CLI and review a diff |
| API surface | Fixed by the maintainers | Whatever you decide it should be |
| Bundle contents | The whole package, subject to tree-shaking | Only the components you copied |
The trade-off is plain. You gain full control and no API wall. You take on responsibility for maintenance, because nobody ships you a patch release for a file you own.
The layers underneath
A shadcn/ui component is a thin composition of tools you already know. Each layer has one job.
- Radix UI primitives provide behavior: focus management, keyboard handling, ARIA attributes, and open/closed state. They ship no visual styles.
- Tailwind CSS provides appearance through utility classes and theme tokens defined as CSS variables.
- cva and cn turn a set of style choices into a final class string.
cvadeclares variants, andcnmerges class names so conflicts resolve predictably. - The copied file is where these pieces are wired together. It is ordinary TypeScript and JSX.
Because the behavior comes from Radix, you can restyle or restructure a component without breaking its accessibility. The reverse also holds. If you remove a Radix part, you lose the behavior it provided.
Reading a copied component
Open any file in components/ui and you will find the same pattern. Here is a dialog in the shadcn/ui style, reduced to the essentials:
import * as React from "react"
import * as DialogPrimitive from "@radix-ui/react-dialog"
import { cn } from "@/lib/utils"
const Dialog = DialogPrimitive.Root
const DialogTrigger = DialogPrimitive.Trigger
const DialogClose = DialogPrimitive.Close
const DialogTitle = DialogPrimitive.Title
const DialogDescription = DialogPrimitive.Description
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DialogPrimitive.Portal>
<DialogPrimitive.Overlay className="fixed inset-0 bg-black/50" />
<DialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 rounded-md bg-background p-6 shadow-lg",
className
)}
{...props}
>
{children}
</DialogPrimitive.Content>
</DialogPrimitive.Portal>
))
DialogContent.displayName = DialogPrimitive.Content.displayName
export {
Dialog,
DialogTrigger,
DialogClose,
DialogTitle,
DialogDescription,
DialogContent,
}Several conventions show up here, and they repeat across the whole set:
- Most parts are re-exports.
Dialog,DialogTrigger, and similar names point straight at Radix. They exist so your app imports everything from one local file. - Styled parts are wrappers.
DialogContentadds the portal, overlay, and default classes, and passes every other prop through with{...props}. classNamegoes throughcnlast. A caller's classes come after the defaults, so a caller can override a default such asp-6withp-10.forwardRefis used throughout. Refs reach the underlying DOM element, which Radix and other libraries rely on.- Types derive from the primitive.
ComponentPropsWithoutRef<typeof DialogPrimitive.Content>means your wrapper accepts every prop Radix does, with no hand-written interface to drift out of date.
None of this is hidden behind a build step. If a prop is missing, you add it.
Modifying a component you own
Since the file is yours, customization is normal editing, not a workaround. Suppose you want a Badge with a status variant your product needs. In a conventional library you might write a styled wrapper or fight specificity. Here you edit the variants:
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const badgeVariants = cva(
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold",
{
variants: {
variant: {
default: "border-transparent bg-primary text-primary-foreground",
outline: "text-foreground",
success: "border-transparent bg-green-600 text-white",
},
},
defaultVariants: { variant: "default" },
}
)
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof badgeVariants> {}
export function Badge({ className, variant, ...props }: BadgeProps) {
return <div className={cn(badgeVariants({ variant }), className)} {...props} />
}The success variant is three lines in a file you control. VariantProps picks it up automatically, so <Badge variant="success"> type-checks and <Badge variant="succes"> does not.
There are two levels of customization, and it helps to choose deliberately:
- Per use. Pass a
classNameat the call site. This suits one-off layout tweaks such as margins or width. - Per component. Edit the file. This suits changes that should apply everywhere, such as a new variant, new default sizing, or extra markup.
If you find yourself passing the same className in many places, that is a signal to move it into the component.
What the CLI actually does
The CLI is a delivery mechanism. It does not stay in your runtime or your build.
npx shadcn@latest init
npx shadcn@latest add button dialoginit configures the project and writes components.json, which records choices such as your import aliases and where components go. add copies the chosen component files into your codebase and installs the npm packages those files need, for example @radix-ui/react-dialog or class-variance-authority. Those packages are ordinary dependencies of your app. The component files themselves are not a dependency of anything.
A consequence worth remembering: components.json is configuration for the CLI only. Deleting it would not break your running application, but it would stop add from knowing where to put files.
Edge cases and gotchas
- Registry components may depend on each other. Adding one component can also add others it imports, such as a
buttonpulled in by a dialog or alert component. Check the diff before you commit. - Re-adding overwrites. Running
addfor a component that already exists can replace your edits. The CLI asks before overwriting, and committing first lets you review what changed. - You inherit Radix's constraints. Components such as
Dialogneed a title for screen readers. Radix logs a development warning if one is missing, and removingDialogTitlefrom a copied component to tidy the markup trades accessibility for convenience. - Variant names are not standardized. Because every team edits its own files,
variant="success"in your project means nothing elsewhere. Document your additions. - Divergence is real. After a few months of edits, your
Buttonmay look little like the registry version. That is by design, but it affects how you take upstream updates, which a later chapter covers.
When this model fits
The copy-and-own model works well when you want a custom look, have designers who will change the visuals, or need components that deviate from a library's defaults. It works less well when you want a single dependency that receives security and bug fixes automatically, or when many teams must share one component version. In that case, wrapping a conventional package, or publishing your own copied components as an internal package, may suit better.
Exercise
A teammate says, "We should upgrade shadcn/ui by bumping its version in package.json." Why does this not apply, and what is the actual way to get a newer version of a component? Name one risk of that method.
Show answer
shadcn/ui is not installed as a package that provides the components. The CLI copies the source files into your repository, so there is no shadcn/ui version to bump. To get a newer version, re-run npx shadcn@latest add <component> and review the resulting diff. The risk is that the command can overwrite local edits you made to that file, so commit first and merge the changes you want to keep by hand.
Exercise
In the Badge example, why is className passed as the second argument to cn instead of the first?
Show answer
cn uses tailwind-merge, which resolves conflicting Tailwind utilities so that the later class wins. Putting the caller's className last lets it override the variant defaults, for example replacing px-2.5 with px-4. If it came first, the defaults would override the caller.