button: support Radix-style asChild via base-ui render prop bridge

The project uses @base-ui/react, whose Button has no asChild prop —
just a `render` prop that takes a React element to merge into. About
14 call sites across the routes still use the Radix-shaped
`<Button asChild><Link to="…">…</Link></Button>` pattern, which until
now was producing nested-button DOM violations and asChild leaking as
a DOM attribute.

Bridges asChild → render inside the Button wrapper:

  <Button asChild><Link to="/login">Sign in</Link></Button>

…now renders as a single <a class="…btn classes…">Sign in</a> instead
of <button asChild><a>…</a></button>.

No call-site changes required; consumers keep the Radix ergonomic and
get correct DOM under the hood.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
jules
2026-05-02 19:57:53 +10:00
parent 7eb5093071
commit 2a68389121

View File

@@ -1,3 +1,4 @@
import * as React from "react"
import { Button as ButtonPrimitive } from "@base-ui/react/button"
import { cva, type VariantProps } from "class-variance-authority"
@@ -40,19 +41,61 @@ const buttonVariants = cva(
}
)
/**
* Button component.
*
* Supports the Radix-style `asChild` ergonomic for cases like
* `<Button asChild><Link to="/foo">…</Link></Button>` so the consumer doesn't
* have to reach for base-ui's `render` prop directly. Internally translates
* `asChild` → base-ui `render` so the underlying `<a>` (or whatever the child
* is) actually rendered, instead of nesting a `<button>` around it.
*/
type ButtonProps = ButtonPrimitive.Props &
VariantProps<typeof buttonVariants> & {
/**
* When true, render the single child element instead of a `<button>`.
* Compatible with Radix-style usage. Internally bridged to base-ui's
* `render` prop.
*/
asChild?: boolean
}
function Button({
className,
variant = "default",
size = "default",
asChild,
children,
render,
...props
}: ButtonPrimitive.Props & VariantProps<typeof buttonVariants>) {
}: ButtonProps) {
const mergedClassName = cn(buttonVariants({ variant, size, className }))
// asChild: take the single child element, hand it to base-ui as the render
// target. base-ui merges its props (including className) into the element.
if (asChild) {
const child = React.Children.only(children) as React.ReactElement
return (
<ButtonPrimitive
data-slot="button"
className={mergedClassName}
render={child}
{...props}
/>
)
}
return (
<ButtonPrimitive
data-slot="button"
className={cn(buttonVariants({ variant, size, className }))}
className={mergedClassName}
render={render}
{...props}
/>
>
{children}
</ButtonPrimitive>
)
}
export { Button, buttonVariants }
export type { ButtonProps }