HomeDocsComponentsBlocksForm contractValidation
Components / ColorInput

ColorInput

Accepts hex, rgb() and hsl(), emits hex, and shows the contrast ratio against a colour you nominate. minContrast raises a warning, not an error — an unreadable brand colour is a legal value and blocking the form over it is the wrong call.

$ npx shadcn@latest add https://input-cn.vercel.app/r/color-input.json
Build with an agent

Hand this to Claude Code

1,723 chars

Most people reach this component through an agent rather than by reading the page. Pick how you want it wired and take a prompt that already carries the canonical value, the real prop names and the mistakes worth avoiding.

Wiring
Extras
Open in Claude Code

Nothing runs on its own. The link opens the tool with the prompt typed into the box; you read it and press Enter. If the button does nothing, Claude Code is not installed on this machine — use Copy prompt instead.

Live demo

1.28:1below AA against #FFFFFF

Paste rgb(205, 242, 92) — it converts.

value = #CDF25C · hex

Constraints

Validation rules, declared as props. Each one produces its own message and its own data-rule value, so a test can assert the rule rather than the sentence.

PROPTYPEDESCRIPTION
contrastAgainst?stringCheck contrast against this colour. The differentiating constraint: it stops a customer picking a brand colour nobody can read.
minContrast?numberMinimum WCAG ratio. 4.5 is AA for body text, 3 is AA for large text.
allowed?readonly string[]Restrict to a palette.

Props

PROPTYPEDESCRIPTION
outputFormat?ColorFormatOutput format for `onChange`. Default "hex" — the only lossless one.
swatches?readonly string[]Palette shown beneath the field.
label?ReactNodeVisible label. Supply this or `aria-label` — a field with neither has no accessible name.
hint?ReactNodeHelper text under the field. Replaced by the error message while one is showing.
nativePicker?booleanShow the native OS picker alongside the text field. Default true.
showSwatches?booleanShow the swatch palette. Default true.
showContrast?booleanShow the live contrast reading when `contrastAgainst` is set. Default true.

Shared props

Implemented identically by all eleven components. These tables are generated from the source interfaces at build time, so a renamed prop changes this page rather than quietly making it wrong.

PROPTYPEDESCRIPTION
value?TCanonical value. Controlled mode.
defaultValue?TCanonical value. Uncontrolled mode. Mutually exclusive with `value`.
onChange?(value: T) => voidEmits the canonical value — never a DOM event.
onBlur?() => voidFires when focus leaves the whole component, not between its parts.
name?stringApplied to the hidden canonical input so FormData carries the real value.
disabled?boolean—
readOnly?boolean—
required?boolean | string—
validate?(value: T) => true | stringCustom synchronous rule. Return true, or the message to display.
messages?MessageMapOverride built-in messages by rule name.
showError?ShowErrorDefault `"touched"`.
onValidityChange?(state: ValidityState) => voidReports validity upward regardless of mode.
mode?FieldModeForce a mode instead of auto-detecting. Escape hatch only.
variant?FieldVariantSurface treatment. Default `"outline"`.
size?FieldSizeDensity. Default `"default"` (32px).
id?string—
className?string—
placeholder?string—
autoFocus?boolean—
aria-label?string—
aria-labelledby?string—
aria-describedby?string—
aria-invalid?boolean | "true" | "false"—

With react-hook-form

import { useForm, Controller } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { colorSchema } from "@inputcn/color/schema"
import { ColorInput } from "@/components/ui/color-input"
import { z } from "zod"

// The companion schema validates the CANONICAL value, so the resolver and the
// field can never disagree about what "valid" means.
const schema = z.object({ brand: colorSchema() })

export function Example() {
  const { control } = useForm({ resolver: zodResolver(schema) })

  return (
    <Controller
      name="brand"
      control={control}
      render={({ field, fieldState }) => (
        <ColorInput
          label="Brand colour"
          {...field}
          aria-invalid={fieldState.invalid}
        />
      )}
    />
  )
}

With a Server Action

import { ColorInput } from "@/components/ui/color-input"

export default function Page() {
  return (
    <form action={save}>
      <ColorInput name="brand" label="Brand colour" />
      <button>Save</button>
    </form>
  )
}

async function save(data: FormData) {
  "use server"
  // The hidden canonical input carries the real value, not the display text.
  const brand = data.get("brand") // "#CDF25C"
}

Keyboard

KEYDOES
Enter / SpaceApplies the focused swatch.
TabSkips the native colour picker, which is a mouse affordance only.

Worth knowing

HSL round-trips are lossy by ±1 in each channel because the conversion rounds to integers. Hex in, hex out is stable; hex → HSL → hex may move by one.

Emits string, for example "#CDF25C". Keyboard operation is covered by automated tests; screen readers have not been verified yet.