Label
An accessible label for form controls.
Installation
$
npx shadcn@latest add https://ui.mattdowney.com/r/label.jsonUsage
import { Label } from "@/components/ui/label"Examples
Default
htmlFor has to match the control's id. That pairing is what lets a click on the label focus the field, and what a screen reader reads out with the control.
API Reference
| Prop | Type | Default | Description |
|---|---|---|---|
| htmlFor | string | None | The id of the form control this label describes. Clicking the label moves focus to that control. |
htmlForstringThe id of the form control this label describes. Clicking the label moves focus to that control. |
"use client"
import * as React from "react"
import { cn } from "@/registry/lib/utils"
// @use-when the name of a form control, bound to it.
function Label({
className,
onMouseDown,
...props
}: React.ComponentProps<"label">) {
return (
<label
data-slot="label"
// leading-tight so a label that wraps has room between its lines, with
// the half-leading taken back off the top and bottom: (1em - 1lh) / 2 is
// -0.125em at 1.25, so the box is exactly one em tall on one line, the
// same as the old leading-none. The label, field and help rungs measure
// from the letters as before, and no form gap moves.
className={cn(
"block text-sm font-medium leading-tight [margin-block:calc((1em-1lh)/2)] peer-disabled:cursor-not-allowed peer-disabled:opacity-70",
className
)}
onMouseDown={(event) => {
// Let clicks that start on an interactive control inside the label
// behave normally (do not treat them as a label double-click).
const target = event.target as HTMLElement
if (target.closest("button, input, select, textarea")) return
onMouseDown?.(event)
// Prevent text selection when double-clicking to toggle a control.
if (!event.defaultPrevented && event.detail > 1) event.preventDefault()
}}
{...props}
/>
)
}
export { Label }