Label
Renders an accessible label associated with controls.
The Label component provides accessible labels for form controls. It properly associates labels with their inputs for screen readers and improves usability. Built from scratch using React and native HTML elements. No dependencies on any UI library.
Code
TypeScript: Copy this code into components/ui/label.tsx:
tsx
import * as React from "react"
import { cn } from "@/lib/utils"
export interface LabelProps extends React.LabelHTMLAttributes<HTMLLabelElement> {}
const Label = React.forwardRef<HTMLLabelElement, LabelProps>(
({ className, ...props }, ref) => {
return (
<label
ref={ref}
className={cn(
"text-sm font-bold leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",
className
)}
{...props}
/>
)
}
)
Label.displayName = "Label"
export { Label }JavaScript: Copy this code into components/ui/label.jsx:
jsx
import * as React from "react"
import { cn } from "@/lib/utils"
const Label = React.forwardRef(
({ className, ...props }, ref) => {
return (
<label
ref={ref}
className={cn(
"text-sm font-bold leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",
className
)}
{...props}
/>
)
}
)
Label.displayName = "Label"
export { Label }Usage
TypeScript:
tsx
import { Label } from "@/components/ui/label"
import { Input } from "@/components/ui/input"
function MyComponent() {
return (
<div className="space-y-2">
<Label htmlFor="email">Email</Label>
<Input id="email" type="email" />
</div>
)
}JavaScript:
jsx
import { Label } from "@/components/ui/label"
import { Input } from "@/components/ui/input"
function MyComponent() {
return (
<div className="space-y-2">
<Label htmlFor="email">Email</Label>
<Input id="email" type="email" />
</div>
)
}Make sure you also have the lib/utils.ts file with the cn helper function.