Sub topic 11
Customizing components you own
This chapter assumes you have run npx shadcn@latest add button dialog, so components/ui/button.tsx exists in your repository. It also assumes you know how cn merges classes and how cva defines variants. Both were covered in earlier chapters.
Because the component source lives in your project, customizing it is ordinary code editing. No theming API or override layer sits in between. The skill is choosing the right place to make each change, so the result stays readable and easy to update.
Four places to change a component
You can change a component at four levels. Start with the cheapest one that solves the problem.
| Level | Where | Use it when | Cost |
|---|---|---|---|
| Call site | `className` on one usage | One screen needs a one-off difference | Lowest, but it spreads if repeated |
| Theme | CSS variables | Every component should change color or radius | Low, with no component edits |
| Component source | `components/ui/*.tsx` | A variant or default should apply everywhere | Medium, because you own the diff |
| Wrapper | A new file that uses the component | You need new behavior or a domain-specific API | Medium, and it leaves the original untouched |
Call-site overrides
The generated Button passes the caller's className last through cn, so the caller wins:
import { Button } from "@/components/ui/button"
export function Toolbar() {
return <Button className="h-12 px-8">Publish</Button>
}The base variants set h-10 px-4 py-2. tailwind-merge sees that h-12 conflicts with h-10 and keeps only the later one. Without it, both classes would stay in the string and the stylesheet's rule order would decide the result.
One-off overrides are fine. If you copy the same className string into a third place, it belongs in a variant.
Adding variants and sizes
Open components/ui/button.tsx and edit the cva call. Here is buttonVariants with a destructive variant, a link variant, and an icon size added:
import { cva, type VariantProps } from "class-variance-authority"
export const buttonVariants = cva(
"inline-flex items-center justify-center rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 disabled:pointer-events-none disabled:opacity-50",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive:
"bg-destructive text-destructive-foreground hover:bg-destructive/90",
outline: "border border-input bg-background hover:bg-accent",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-10 px-4 py-2",
sm: "h-9 px-3",
icon: "h-10 w-10",
},
},
defaultVariants: { variant: "default", size: "default" },
}
)
export type ButtonVariants = VariantProps<typeof buttonVariants>VariantProps derives the TypeScript types from this object. After the edit, <Button variant="destructive" /> type-checks and variant="danger" does not. You never update a separate type by hand.
Use semantic token classes such as bg-destructive rather than raw colors like bg-red-600. The theme then controls them, and dark mode works without extra classes.
Writing a wrapper component
Edit the source when every user of the component should get the change. Write a wrapper when you want a new prop or a new behavior. A loading state is a typical case:
import * as React from "react"
import { Button, type ButtonProps } from "@/components/ui/button"
export interface LoadingButtonProps extends ButtonProps {
loading?: boolean
loadingText?: string
}
const LoadingButton = React.forwardRef<HTMLButtonElement, LoadingButtonProps>(
({ loading = false, loadingText = "Saving…", disabled, children, ...props }, ref) => (
<Button ref={ref} disabled={disabled || loading} aria-busy={loading} {...props}>
{loading ? loadingText : children}
</Button>
)
)
LoadingButton.displayName = "LoadingButton"
export { LoadingButton }The wrapper follows four rules:
- It extends
ButtonProps, so every existing prop and variant still works. - It forwards
ref, so focus management and Radix triggers keep working. - It spreads
...propslast, so attributes likeonClickandtypepass through. - It sets
aria-busy, so assistive technology learns about the pending state. Disabling the button alone does not tell it.
Put wrappers in a different folder from components/ui, for example components/app. The ui folder then holds only code that stays close to the generated source. That makes later diffs against upstream much smaller.
Customizing Radix-based components
Components such as Dialog, DropdownMenu, and Tabs wrap Radix primitives. Radix exposes state through data attributes, and you style those states with Tailwind's arbitrary variants:
import * as Dialog from "@radix-ui/react-dialog"
export function WideDialogContent({ children }: { children: React.ReactNode }) {
return (
<Dialog.Portal>
<Dialog.Overlay className="fixed inset-0 bg-black/50 data-[state=open]:opacity-100 data-[state=closed]:opacity-0 transition-opacity" />
<Dialog.Content className="fixed left-1/2 top-1/2 w-full max-w-2xl -translate-x-1/2 -translate-y-1/2 rounded-md bg-white p-6">
{children}
</Dialog.Content>
</Dialog.Portal>
)
}Here max-w-2xl widens the dialog. The data-[state=...] classes react to Radix's open and closed state. Do not remove the Dialog.Title and Dialog.Description parts when you restyle. Radix uses them to label the dialog for screen readers, and it warns in the console when the title is missing.
Customizing asChild usage
With asChild, Slot merges the button's props and classes onto the child element. This lets a link look like a button:
import { Button } from "@/components/ui/button"
export function DocsLink() {
return (
<Button asChild variant="link">
<a href="/docs">Read the docs</a>
</Button>
)
}The child must accept a ref and spread unknown props onto a DOM element. A custom component that ignores them will lose the styles and the event handlers. Also note that a wrapper like LoadingButton replaces children while loading. Combining it with asChild would pass a string to Slot instead of one element, so avoid that combination.
Teaching tailwind-merge your own classes
twMerge knows the built-in Tailwind classes. If you add a custom utility such as text-title through your Tailwind config, it cannot tell which group the class belongs to. It may then drop a class it should keep, or fail to remove a conflicting one. Register the custom names in lib/utils.ts:
import { clsx, type ClassValue } from "clsx"
import { extendTailwindMerge } from "tailwind-merge"
const twMerge = extendTailwindMerge({
extend: {
classGroups: {
"font-size": [{ text: ["title", "caption"] }],
},
},
})
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}Now cn("text-sm", "text-title") keeps only text-title.
Keeping customizations maintainable
- Commit the untouched generated file before you edit it. Your edits then show as a clean diff, which helps when you compare against a newer upstream version.
- Prefer variants over scattered
classNamestrings. A variant has a name, and it appears in autocomplete. - Keep edits to
components/uismall and additive: new variants, new sizes, changed defaults. Large rewrites make later updates hard. - Record why a change exists in a short comment, especially when you deviate from upstream behavior.
- Move new behavior into wrappers, so the generated files stay close to upstream.
Exercise
A teammate wants every Button in the app to show a "loading" state with a spinner and block clicks while pending. They plan to add loading handling directly inside components/ui/button.tsx and also add className="bg-red-600" at each place that needs a danger button. Which two changes would you suggest instead, and why?
Show answer
Put the loading behavior in a wrapper such as LoadingButton in a separate folder. It adds the new prop and sets disabled and aria-busy, and the generated file stays close to upstream. This also avoids breaking asChild usage, where the extra logic would replace the child. For the danger style, add a destructive variant to the cva definition that uses the bg-destructive token. Every call site then writes variant="destructive", the type is checked, and the theme controls the color in light and dark mode.