UIPin
ComponentsIconsIllustrationsMotionTemplatesApps
Boards
UIPin

Free, open-source UI components, icons, illustrations, motion, templates and apps, in one search. Every item links to its source and licence.

UIPin is free. If it saved you time, you can keep it running:

Buy me a coffee
ComponentsIconsIllustrationsMotionTemplatesAppsLibrariesCompareNew this weekMCP for agentsBoardsPrivacy

Components, icons and artwork belong to their authors and are shown under their open-source licences.

HextaUI/Label

Inputs & forms
1 of 3
Compiling

Theme it

Every preview, live

Brand colour

Corner radius

Font

Recolours shadcn’s tokens, Tailwind’s accent colours and colours set in the code. Red, amber and green classes stay, since they usually mean error, warning or success.

3 versions·3 libraries

  • HextaUI
  • 8bitcn
  • shadcn/ui

Label

A label that follows its control, dimming when it's disabled and marking it required or optional on its own.

npx shadcn@latest add https://hextaui.com/r/label.json
Open in v0 Docs Repo
Library
HextaUI
License
MIT
Stack
React · Tailwind CSS · animated · base-ui
Packages
@base-ui/react@tabler/icons-reactclass-variance-authoritycnshadcntw-animate-css
Also adds
checkbox, input, motion, number-flow, use-autosize, use-composed-ref, use-invalid-shake, use-merged-ref
Size
245 lines
Demo
From HextaUI

Code

components/ui/label.tsx

"use client"

import * as React from "react"
import { mergeProps } from "@base-ui/react/merge-props"
import { useRender } from "@base-ui/react/use-render"
import { cn } from "cn"

type LabelIndicator = "required" | "optional"

type ControlState = {
  disabled: boolean
  required: boolean
  invalid: boolean
  readOnly: boolean
}

const idleState: ControlState = {
  disabled: false,
  required: false,
  invalid: false,
  readOnly: false,
}

const controlSelector =
  'input:not([type="hidden"]), textarea, select, button, meter, output, progress, [role="checkbox"], [role="switch"], [role="radio"], [role="combobox"], [role="slider"]'

function findControl(label: HTMLLabelElement) {
  if (label.htmlFor) {
    return document.getElementById(label.htmlFor)
  }
  return label.querySelector<HTMLElement>(controlSelector)
}

function readState(control: HTMLElement | null): ControlState {
  if (!control) {
    return idleState
  }
  return {
    disabled:
      control.matches(":disabled") ||
      control.hasAttribute("data-disabled") ||
      control.getAttribute("aria-disabled") === "true",
    required:
      control.matches(":required") ||
      control.getAttribute("aria-required") === "true" ||
      control.hasAttribute("data-required"),
    invalid:
      control.getAttribute("aria-invalid") === "true" ||
      control.hasAttribute("data-invalid") ||
      control.matches(":user-invalid"),
    readOnly:
      control.matches(":read-only:is(input, textarea)") ||
      control.getAttribute("aria-readonly") === "true" ||
      control.hasAttribute("data-readonly"),
  }
}

function sameState(a: ControlState, b: ControlState) {
  return (
    a.disabled === b.disabled &&
    a.required === b.required &&
    a.invalid === b.invalid &&
    a.readOnly === b.readOnly
  )
}

function useControlState(
  labelRef: React.RefObject<HTMLLabelElement | null>,
  htmlFor: string | undefined
) {
  const [state, setState] = React.useState(idleState)

  React.useEffect(() => {
    const label = labelRef.current
    if (!label) {
      return
    }

    let control: HTMLElement | null = null
    let frame = 0
    const attributes = new MutationObserver(() => sync())
    const children = new MutationObserver(() => connect())

    const sync = () => {
      const next = readState(control)
      setState((previous) => (sameState(previous, next) ? previous : next))
    }

    const connect = () => {
      const found = findControl(label)
      if (found === control) {
        return
      }
      control = found
      attributes.disconnect()
      if (control) {
        attributes.observe(control, {
          attributes: true,
          attributeFilter: [
            "disabled",
            "required",
            "readonly",
            "aria-disabled",
            "aria-required",
            "aria-invalid",
            "aria-readonly",
            "data-disabled",
            "data-required",
            "data-invalid",
            "data-readonly",
          ],
        })
      }
      sync()
    }

    const onFieldEvent = (event: Event) => {
      if (control && event.target === control) {
        sync()
      }
    }

    connect()
    if (!control) {
      frame = requestAnimationFrame(connect)
    }
    if (!htmlFor) {
      children.observe(label, { childList: true, subtree: true })
    }
    window.addEventListener("input", onFieldEvent)
    window.addEventListener("change", onFieldEvent)
    window.addEventListener("focusout", onFieldEvent)
    window.addEventListener("invalid", onFieldEvent, true)

    return () => {
      cancelAnimationFrame(frame)
      attributes.disconnect()
      children.disconnect()
      window.removeEventListener("input", onFieldEvent)
      window.removeEventListener("change", onFieldEvent)
      window.removeEventListener("focusout", onFieldEvent)
      window.removeEventListener("invalid", onFieldEvent, true)
    }
  }, [labelRef, htmlFor])

  return state
}

type LabelProps = useRender.ComponentProps<"label"> & {
  indicator?: LabelIndicator
  optionalText?: React.ReactNode
}

function Label({
  className,
  indicator,
  optionalText = "Optional",
  render,
  children,
  htmlFor,
  onMouseDown,
  ref,
  ...props
}: LabelProps) {
  const labelRef = React.useRef<HTMLLabelElement | null>(null)
  const state = useControlState(labelRef, htmlFor)
  const setRef = React.useCallback(
    (node: HTMLLabelElement | null) => {
      labelRef.current = node
      if (typeof ref === "function") {
        return ref(node)
      }
      if (ref) {
        ref.current = node
      }
      return undefined
    },
    [ref]
  )

  const mark =
    indicator === "required" && state.required ? (
      <span
        aria-hidden="true"
        data-slot="label-indicator"
        data-indicator="required"
        className="-ms-1.5 shrink-0 self-start font-normal whitespace-nowrap text-muted-foreground"
      >
        *
      </span>
    ) : indicator === "optional" && !state.required ? (
      <span
        aria-hidden="true"
        data-slot="label-indicator"
        data-indicator="optional"
        className="shrink-0 self-start font-normal whitespace-nowrap text-muted-foreground"
      >
        {optionalText}
      </span>
    ) : null

  return useRender({
    defaultTagName: "label",
    render,
    ref: setRef,
    props: mergeProps<"label">(
      {
        htmlFor,
        className: cn(
          "inline-flex w-fit max-w-full min-w-0 items-center gap-2 text-sm leading-snug font-medium text-pretty wrap-anywhere text-foreground select-none data-disabled:cursor-not-allowed data-disabled:opacity-50 [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-muted-foreground",
          className
        ),
        onMouseDown: (event) => {
          onMouseDown?.(event)
          const target = event.target as Element
          if (
            !event.defaultPrevented &&
            event.detail > 1 &&
            !target.closest(controlSelector)
          ) {
            event.preventDefault()
          }
        },
        children: (
          <>
            {children}
            {mark}
          </>
        ),
      },
      props,
      {
        "data-slot": "label",
        ...(state.disabled ? { "data-disabled": "" } : {}),
        ...(state.required ? { "data-required": "" } : {}),
        ...(state.invalid ? { "data-invalid": "" } : {}),
        ...(state.readOnly ? { "data-readonly": "" } : {}),
      } as React.ComponentProps<"label">
    ),
  })
}

export { Label }
export type { LabelIndicator, LabelProps }

More like this

Checkbox

HextaUI·Inputs & forms

Textarea

shadcn/ui·Text effects

Command

shadcn/ui·Overlays

Native select

HextaUI·Inputs & forms

Input

shadcn/ui·Inputs & forms

Ai Prompt Input

SmoothUI·Inputs & forms

Bento Grid

Magic UI·Cards

Transition Panel

Motion Primitives·Other

Page Transition

Animate UI·NavigationMIT+

Item

shadcn/ui·Other

Alert

HextaUI·Feedback & loaders

Alert

SmoothUI·Feedback & loaders

Scroll Area

shadcn/ui·Data display

Combobox

HextaUI·Inputs & forms

Animated File Upload

SmoothUI·Inputs & forms