Menu

Components

Color Field

A field for typing a color: the hex code, or one number of it such as the hue. Built on react-aria-components.

Introduction

Color Field is for a color you have as a code: paste a hex from a design file, type one you know, or fix a digit. A small square shows the color as it is committed. With channel it edits one number of a color instead, such as the hue or the red, which is how a color picker lets you tune a color exactly.

  • Built on react-aria's ColorField, so keyboard support, screen readers, form submission and validation come from there.
  • What is typed is read when the field loses focus or Enter is pressed. A text that is not a color goes back to the last one, and three digits mean six: #38f is #3388ff. The # can be left out.
  • The color is a plain string in CSS, and goes back as hex, rgb, hsl or hsb. It is null when the field is emptied.
  • A channel field holds a number that the arrow keys and the mouse wheel step. Several of them share one color, and the other channels do not change while you edit one, hue included.
  • It pairs with ColorArea: type in one and the other follows.

It is a Client Component. The hex is written in a monospace font so the digits line up.

Installation

centerUI has no CLI or registry yet: components are copied into your project.

# bun
bun add react-aria-components tailwind-variants tailwind-merge clsx

# pnpm
pnpm add react-aria-components tailwind-variants tailwind-merge clsx

# npm
npm install react-aria-components tailwind-variants tailwind-merge clsx

Manual installation

Copy these files into your project and keep the paths, or adjust the imports.

1. Add the styles

src/types/color-field-styles.tsShow code
import { tv } from "tailwind-variants";

// The frame around the swatch, the prefix, the input and the suffix. It is a plain
// element, not the input itself, so everything sits inside one border and the
// focus ring wraps all of it.
export const colorFieldStyles = tv({
  slots: {
    frame: [
      "flex w-full items-center gap-2 rounded-md text-fg transition-colors",
      "focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 focus-within:ring-offset-bg",
      "group-data-invalid/color-field:border-danger",
      "group-data-disabled/color-field:pointer-events-none group-data-disabled/color-field:opacity-50",
      "[&_svg]:shrink-0",
    ],
    addon: "flex shrink-0 items-center text-muted-fg",
    // The color it holds, in a small square before the input.
    swatch: "size-4 shrink-0 rounded-[4px] border",
    input:
      "min-w-0 flex-1 bg-transparent font-mono outline-none placeholder:font-sans placeholder:text-muted-fg read-only:cursor-default",
  },
  variants: {
    variant: {
      outline: { frame: "border bg-transparent" },
      secondary: { frame: "bg-secondary text-secondary-fg" },
      ghost: { frame: "bg-transparent focus-within:bg-muted hover:bg-muted" },
    },
    size: {
      sm: {
        frame: "px-2.5 text-sm",
        addon: "text-sm [&_svg]:size-4",
      },
      md: {
        frame: "px-3 text-sm",
        addon: "text-sm [&_svg]:size-4",
      },
      lg: {
        frame: "px-3.5 text-base",
        addon: "text-base [&_svg]:size-5",
      },
    },
  },
  compoundVariants: [
    { size: "sm", class: { frame: "h-8", input: "h-full" } },
    { size: "md", class: { frame: "h-9", input: "h-full" } },
    { size: "lg", class: { frame: "h-11", input: "h-full" } },
  ],
  defaultVariants: { variant: "outline", size: "md" },
});

2. Add the Color Field file

src/components/ui/color-field/color-field.tsxShow code
"use client";

import { type ReactNode, useState } from "react";
import {
  ColorField as AriaColorField,
  type Color,
  type ColorChannel,
  FieldError,
  Input,
  Label,
  parseColor,
  Text,
  type ValidationResult,
} from "react-aria-components";
import { cn } from "@/lib/cn";
import { colorFieldStyles } from "@/types/color-field-styles";

/** The color spaces a single channel can belong to. */
export type ColorFieldSpace = "hsb" | "hsl" | "rgb";

/** How the color is written when it is given back. */
export type ColorFieldFormat = "hex" | "rgb" | "hsl" | "hsb";

export interface ColorFieldProps {
  label?: ReactNode;
  /** Help text under the field. */
  description?: ReactNode;
  /** Shown when the field is invalid. A function receives the validation result. */
  errorMessage?: string | ((validation: ValidationResult) => string);
  /** The color, written in CSS: `"#3b82f6"`, `"rgb(59, 130, 246)"`, `"hsl(217, 91%, 60%)"` or `"hsb(217, 76%, 96%)"`; `null` for none. For a controlled field. */
  value?: string | null;
  /** The color to start with, for an uncontrolled field. */
  defaultValue?: string | null;
  /** Called with the color, written in `format`, when the user commits what they typed, and `null` when the field is emptied. */
  onChange?: (color: string | null) => void;
  /**
   * Edit one channel of the color as a number, such as the hue, instead of the
   * whole color as hex. The field then shows a number, the arrow keys and the
   * mouse wheel step it, and `value` is still the whole color.
   */
  channel?: ColorChannel;
  /** The color space of `channel`. Defaults to `hsb`. */
  colorSpace?: ColorFieldSpace;
  /** How the color is written when it is given back. Defaults to `hex`. */
  format?: ColorFieldFormat;
  /** A small square of the color before the input. Defaults to `true`, and not shown when the field edits one channel. */
  showSwatch?: boolean;
  placeholder?: string;
  /** An icon or a short text before the input, after the swatch. */
  prefix?: ReactNode;
  /** An icon or a short text after the input, such as a unit. */
  suffix?: ReactNode;
  /** The mouse wheel does not change a channel while the field has focus. */
  isWheelDisabled?: boolean;
  variant?: "outline" | "secondary" | "ghost";
  size?: "sm" | "md" | "lg";
  name?: string;
  form?: string;
  autoFocus?: boolean;
  isDisabled?: boolean;
  isReadOnly?: boolean;
  isInvalid?: boolean;
  isRequired?: boolean;
  "aria-label"?: string;
  className?: string;
}

function toColor(
  text: string | null | undefined,
  space: ColorFieldSpace | null,
): Color | null {
  if (!text) return null;
  try {
    const color = parseColor(text);
    return space ? color.toFormat(space) : color;
  } catch {
    return null;
  }
}

// Written in lower case, as CSS is usually written: react-aria writes hex in capitals.
const write = (color: Color, format: ColorFieldFormat) => {
  const text = color.toString(format);
  return format === "hex" ? text.toLowerCase() : text;
};

// Two colors are the same when they read the same in the space they are kept in:
// hex for the whole color, and for a channel field all of the channels of its
// space, because two colors can share a hex and differ in a hue that hex loses.
const sameColor = (
  a: Color | null,
  b: Color | null,
  space: ColorFieldSpace | null,
) => {
  const form = space ?? "hex";
  return (a?.toString(form) ?? null) === (b?.toString(form) ?? null);
};

/**
 * A field for typing a color: the hex code, `#3b82f6`, or, with `channel`, one
 * number of the color such as its hue or its red. A small square shows the
 * color as it is typed. Built on react-aria's ColorField, so keyboard support,
 * screen reader support, form submission (`name`) and validation come from
 * there.
 *
 * It takes a color as it is typed and keeps the last good one: what is typed
 * is read when the field loses focus or Enter is pressed, and a text that is
 * not a color goes back to the last color. Three digits (`#38f`) mean six
 * (`#3388ff`). The color is a plain string in CSS, so it can come from a
 * form or a database, and goes back as hex unless you choose another `format`.
 * Fields that share one color through a string should use a `format` that keeps
 * every channel (`hsb` or `hsl`), because a hex loses the hue of a gray or black.
 *
 * @example
 * <ColorField label="Brand color" defaultValue="#3b82f6" onChange={setColor} />
 * <ColorField label="Hue" channel="hue" value={color} onChange={setColor} />
 */
export function ColorField({
  label,
  description,
  errorMessage,
  value,
  defaultValue,
  onChange,
  channel,
  colorSpace = "hsb",
  format = "hex",
  showSwatch = true,
  placeholder,
  prefix,
  suffix,
  isWheelDisabled,
  variant,
  size = "md",
  className,
  ...props
}: ColorFieldProps) {
  const styles = colorFieldStyles({ variant, size });
  // With a channel the color is kept in the space of the channel, so the other
  // channels are not changed by a round trip through hex.
  const space = channel ? colorSpace : null;
  const [color, setColor] = useState<Color | null>(() =>
    toColor(value !== undefined ? value : defaultValue, space),
  );

  // A controlled field follows its value, but only when it is really another
  // color: the one it gave back comes round again, and must not change what it
  // holds (a hue that hex cannot keep, for one).
  if (value !== undefined) {
    const next = toColor(value, space);
    if (!sameColor(next, color, space)) setColor(next);
  }

  return (
    <AriaColorField
      {...props}
      value={color}
      channel={channel}
      colorSpace={colorSpace}
      isWheelDisabled={isWheelDisabled}
      onChange={(next) => {
        setColor(next);
        onChange?.(next ? write(next, format) : null);
      }}
      // Show a problem while the user types, not only on submit.
      validationBehavior="aria"
      className={cn(
        "group/color-field flex w-full flex-col gap-1.5",
        className,
      )}
    >
      {label ? (
        <Label className="text-sm font-medium group-data-required/color-field:after:ml-0.5 group-data-required/color-field:after:text-danger group-data-required/color-field:after:content-['*']">
          {label}
        </Label>
      ) : null}
      <div className={styles.frame()}>
        {showSwatch && !channel ? (
          <span
            aria-hidden="true"
            className={cn(
              styles.swatch(),
              // No color yet: a dashed empty square.
              color === null && "border-dashed",
            )}
            style={color ? { background: color.toString("css") } : undefined}
          />
        ) : null}
        {prefix ? <span className={styles.addon()}>{prefix}</span> : null}
        <Input placeholder={placeholder} className={styles.input()} />
        {suffix ? <span className={styles.addon()}>{suffix}</span> : null}
      </div>
      {description ? (
        <Text slot="description" className="text-sm text-muted-fg">
          {description}
        </Text>
      ) : null}
      <FieldError className="text-sm text-danger">{errorMessage}</FieldError>
    </AriaColorField>
  );
}

3. Use it

import { ColorField } from "@/components/ui/color-field/color-field";

Anatomy

A framed input with a swatch of the color in front.

<ColorField
  label="Brand color"
  description="Used for buttons and links."
  defaultValue="#3b82f6"
  onChange={(color) => console.log(color)} // "#3b82f6", or null when emptied
/>
PartRendered asNotes
LabellabelNames the field. Clicking it focuses the input.
SwatchspanA small square of the color, updated as it is committed. Dashed and empty while there is no color.
InputinputThe hex code in a monospace font. With channel, a number instead.
Prefix / suffixspanAn icon or a short text before and after the input, such as a unit.
Description / errortext under the fieldHelp text, replaced by the error message when the field is invalid.

Without a label, give the field an aria-label so a screen reader can name it.

Value

The color is text in CSS, and goes back in the format you choose.

// Any color in CSS. It goes back in the format you choose (hex by default),
// and null when the field is emptied.
"#3b82f6"
"rgb(59, 130, 246)"
"hsl(217, 91%, 60%)"
"hsb(217, 76%, 96%)"

Keyboard

It is a text input, and a channel field adds steps.

KeyWhat it does
Type, then Enter or leave the fieldRead what was typed. A text that is not a color goes back to the last color.
Arrow Up, Arrow DownIn a channel field, add or subtract one from the number.
Page Up, Page DownIn a channel field, step by a larger amount.
Mouse wheelIn a channel field that has focus, step the number. Turn it off with isWheelDisabled.

Examples

Usage

Type a hex code and press Enter, or leave the field.

Label

Description

Used for buttons and links.

Default value

Start with a color, in any CSS form.

Placeholder

A hint in an empty field.

Controlled

Keep the color in your own state with value and onChange. It is null while the field is empty.

value: "#3b82f6"

With a color area

A field and an area that hold one color: drag the thumb and the hex changes, type a hex and the thumb moves.

One channel

channel makes the field edit one number of the color. Several fields with the same value edit the same color, and the arrow keys step the number. Give the color back as hsb, as here, so that fields sharing it through a string keep the hue of a black or gray color: a hex cannot.

°
%
%

Red, green and blue

colorSpace chooses the space the channel belongs to: hsb by default, or hsl, or rgb for red, green and blue.

Formats

format decides how the color is written when it is given back. The field itself still shows hex.

Gives back rgb(...).

Swatch

The square of the color is on by default. Turn it off, or use a # prefix instead.

#

Prefix and suffix

An icon or a short text before and after the input.

hex

Sizes

Variants

In a form

With a name, the color is submitted as hex.

Not submitted yet.

Disabled and read only

Validation

For a rule of your own, set isInvalid with an errorMessage. Here white text must be readable on the color.

It needs white text on it.That color is too light for white text.

Component API

Color Field takes the props below.

PropTypeDefault
labelReactNode-
descriptionReactNode-
errorMessagestring | (validation) => string-
valuestring | null-
defaultValuestring | null-
onChange(color: string | null) => void-
channelColorChannel- (the whole color, as hex)
colorSpace"hsb" | "hsl" | "rgb""hsb"
format"hex" | "rgb" | "hsl" | "hsb""hex"
showSwatchbooleantrue
placeholderstring-
prefixReactNode-
suffixReactNode-
isWheelDisabledbooleanfalse
namestring-
variant"outline" | "secondary" | "ghost""outline"
size"sm" | "md" | "lg""md"
autoFocusbooleanfalse
isDisabledbooleanfalse
isReadOnlybooleanfalse
isInvalidbooleanfalse
isRequiredbooleanfalse
aria-labelstring- (when there is no label)