Menu

Components

Color Picker

An area, sliders, a hex field and swatches that hold one color: pick it, tune it, or type it.

Introduction

Color Picker puts everything for choosing a color in one place: a square for the saturation and the brightness, a slider for the hue, and, if you want them, a slider for the opacity, a field for the hex code, a row of ready-made colors and an eyedropper. They all hold one color, so a change in one shows in the others.

  • Built on react-aria's ColorArea and ColorSlider: mouse, touch and keyboard all work, and a screen reader hears each channel and its value.
  • The color is a plain string in CSS, such as "#3b82f6", and goes back as hex, rgb, hsl or hsb. With showAlpha it carries an opacity too, as in #3b82f680.
  • The hue that a hex loses when the color is gray or black is kept in the picker, so the sliders do not jump when you drag to black and back.
  • swatches lists colors to pick in one press, and the eyedropper picks one from anywhere on the screen in the browsers that have it.
  • It can stay on the page, or, with isPopover, be a button with the color in it that opens the picker.

For the pieces on their own, see ColorArea and ColorField. It is a Client Component.

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. It uses Color Field, Button and the pipette icon.

1. Add Color Field

The hex field of the picker, as described on its page.

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>
  );
}

2. Add the styles

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

// Styles for ColorPicker. The gradients of the area and the sliders, and the
// place of the thumbs, are set by react-aria from the color as inline styles, so
// they are not here: only sizes, corners, thumbs and rings are.
export const colorPickerStyles = tv({
  slots: {
    root: "flex flex-col gap-1.5 text-fg",
    // The panel with the area, sliders, field and swatches, as a card or bare.
    panel: "flex flex-col gap-3",
    area: [
      "relative aspect-[4/3] w-full shrink-0 rounded-lg outline-none",
      "data-focus-visible:ring-2 data-focus-visible:ring-ring data-focus-visible:ring-offset-2 data-focus-visible:ring-offset-bg",
      "data-disabled:cursor-not-allowed data-disabled:opacity-60",
    ],
    slider: "flex w-full flex-col",
    track: [
      "relative h-4 w-full rounded-full",
      "data-disabled:cursor-not-allowed data-disabled:opacity-60",
    ],
    row: "flex items-center gap-2",
    swatches: "flex flex-wrap gap-1.5",
    swatch: [
      "size-6 shrink-0 cursor-pointer rounded-md border outline-none transition-transform",
      "hover:scale-110 motion-reduce:transition-none motion-reduce:hover:scale-100",
      "focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-bg",
      "aria-pressed:ring-2 aria-pressed:ring-fg aria-pressed:ring-offset-2 aria-pressed:ring-offset-bg",
      "disabled:pointer-events-none disabled:opacity-50",
    ],
    triggerSwatch: "size-5 shrink-0 rounded-[4px] border",
    triggerValue: "font-mono text-sm tabular-nums",
    popover:
      "z-50 rounded-xl border bg-card p-3 text-card-fg shadow-lg outline-none",
    trigger: "justify-start gap-2 font-normal",
  },
  variants: {
    size: {
      sm: { panel: "w-56" },
      md: { panel: "w-64" },
      lg: { panel: "w-80" },
    },
    variant: {
      card: { panel: "rounded-xl border bg-card p-3 text-card-fg shadow-xs" },
      plain: {},
    },
  },
  defaultVariants: { size: "md", variant: "card" },
});

3. Add the Color Picker file

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

import { type ReactNode, useState, useSyncExternalStore } from "react";
import {
  ColorPicker as AriaColorPicker,
  type Color,
  ColorArea,
  ColorSlider,
  Dialog,
  DialogTrigger,
  Label,
  Popover,
  parseColor,
  SliderTrack,
} from "react-aria-components";
import { PipetteIcon } from "@/components/icons";
import { Button } from "@/components/ui/button/button";
import { ColorField } from "@/components/ui/color-field/color-field";
import { ColorThumb } from "@/components/ui/color-thumb/color-thumb";
import { cn } from "@/lib/cn";
import { colorPickerStyles } from "@/types/color-picker-styles";

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

export interface ColorPickerProps {
  /** The color, written in CSS: `"#3b82f6"`, `"rgb(59, 130, 246)"`, `"hsl(217, 91%, 60%)"` or `"hsb(217, 76%, 96%)"`. For a controlled picker. */
  value?: string;
  /** The color to start with, for an uncontrolled picker. */
  defaultValue?: string;
  /** Called as the color changes, with it written in `format`. */
  onChange?: (color: string) => void;
  /** Called when the thumb is let go, or a key press is done, with the color written in `format`. */
  onChangeEnd?: (color: string) => void;
  /** How the color is written when it is given back. Defaults to `hex`. */
  format?: ColorPickerFormat;
  /** A slider for the opacity, and colors that carry it: `#3b82f680`, `rgba(...)`. Defaults to `false`. */
  showAlpha?: boolean;
  /** Colors to pick in one press, in a row under the sliders. */
  swatches?: string[];
  /** The field to type the hex code in. Defaults to `true`. */
  showInput?: boolean;
  /** A button that picks a color from anywhere on the screen, where the browser has one (Chrome and Edge). Defaults to `true`. */
  showEyeDropper?: boolean;
  /** Show only a button with the color, and open the picker in a popover when it is pressed. Defaults to `false`. */
  isPopover?: boolean;
  /** Names the picker. Shown above the button of a popover picker. */
  label?: ReactNode;
  /** With `isPopover`: which side of the button the popover opens on. Defaults to `bottom start`. */
  placement?: "bottom start" | "bottom end" | "top start" | "top end";
  /** How wide the picker is. Defaults to `md`. */
  size?: "sm" | "md" | "lg";
  /** A card with a border and padding, or nothing around the picker. Defaults to `card`. Not used by a popover, which is a card of its own. */
  variant?: "card" | "plain";
  isDisabled?: boolean;
  "aria-label"?: string;
  className?: string;
}

const fallback = "hsb(220, 80%, 90%)";

function toColor(text: string | undefined): Color {
  try {
    return parseColor(text ?? fallback).toFormat("hsb");
  } catch {
    return parseColor(fallback);
  }
}

// Written in lower case, as CSS is usually written, and with the opacity only
// when there is a slider for it.
const write = (color: Color, format: ColorPickerFormat, alpha: boolean) => {
  const kind = alpha ? (`${format}a` as const) : format;
  const text = color.toString(kind === "hsba" ? "hsba" : kind);
  return format === "hex" ? text.toLowerCase() : text;
};

// The checkerboard behind a color that is not fully opaque.
const checker =
  "repeating-conic-gradient(#cccccc 0% 25%, #ffffff 0% 50%) 50% / 12px 12px";

interface EyeDropperWindow {
  EyeDropper?: new () => { open: () => Promise<{ sRGBHex: string }> };
}

/**
 * A picker for a color: a square for the saturation and the brightness, a
 * slider for the hue, and, if you ask, a slider for the opacity, a field for the
 * hex code, a row of ready-made colors and an eyedropper that picks a color
 * from anywhere on the screen. All of them hold one color, so a change in one
 * shows in the others. It can stay on the page, or, with `isPopover`, be a
 * button with the color that opens the picker.
 *
 * Built on react-aria's ColorArea and ColorSlider, so it works with a mouse, a
 * finger and the keyboard, and screen readers hear the channels and their
 * values. 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`. The hue,
 * which a hex loses when the color is gray or black, is kept in the picker.
 *
 * @example
 * <ColorPicker defaultValue="#3b82f6" onChange={setColor} swatches={["#ef4444", "#22c55e"]} />
 * <ColorPicker isPopover label="Accent color" value={color} onChange={setColor} />
 */
export function ColorPicker({
  value,
  defaultValue,
  onChange,
  onChangeEnd,
  format = "hex",
  showAlpha = false,
  swatches,
  showInput = true,
  showEyeDropper = true,
  isPopover = false,
  label,
  placement = "bottom start",
  size,
  variant,
  isDisabled,
  "aria-label": ariaLabel,
  className,
}: ColorPickerProps) {
  const styles = colorPickerStyles({
    size,
    variant: isPopover ? "plain" : variant,
  });
  const [color, setColor] = useState<Color>(() =>
    toColor(value ?? defaultValue),
  );
  // False on the server and while the page hydrates, true after: only some
  // browsers have an eyedropper.
  const canPipette = useSyncExternalStore(
    () => () => {},
    () => typeof (window as EyeDropperWindow).EyeDropper === "function",
    () => false,
  );

  // A controlled picker follows its value, but only when it is really another
  // color: the one it gave back comes round again, and must not cost the hue
  // that hex cannot hold.
  if (value !== undefined) {
    const next = toColor(value);
    if (next.toString("hexa") !== color.toString("hexa")) setColor(next);
  }

  const out = (next: Color) => write(next, format, showAlpha);
  const hex = color.toString("hex").toLowerCase();
  const isOpaque = color.getChannelValue("alpha") === 1;

  function apply(next: Color) {
    // The picker keeps its color in hsb, so the hue survives a gray or a black.
    const kept = next.toFormat("hsb");
    setColor(kept);
    onChange?.(out(kept));
  }

  async function pipette() {
    const Dropper = (window as EyeDropperWindow).EyeDropper;
    if (!Dropper) return;
    try {
      const picked = await new Dropper().open();
      const next = parseColor(picked.sRGBHex).toFormat("hsb");
      // The opacity is not the eyedropper's to change.
      const kept = showAlpha
        ? next.withChannelValue("alpha", color.getChannelValue("alpha"))
        : next;
      apply(kept);
      onChangeEnd?.(out(kept));
    } catch {
      // The user closed it without picking.
    }
  }

  const panel = (
    <div className={styles.panel()}>
      <ColorArea
        colorSpace="hsb"
        xChannel="saturation"
        yChannel="brightness"
        isDisabled={isDisabled}
        onChangeEnd={(next) => onChangeEnd?.(out(next.toFormat("hsb")))}
        className={styles.area()}
      >
        <ColorThumb />
      </ColorArea>

      <ColorSlider
        colorSpace="hsb"
        channel="hue"
        isDisabled={isDisabled}
        onChangeEnd={(next) => onChangeEnd?.(out(next.toFormat("hsb")))}
        className={styles.slider()}
      >
        <SliderTrack className={styles.track()}>
          <ColorThumb orientation="horizontal" />
        </SliderTrack>
      </ColorSlider>

      {showAlpha ? (
        <ColorSlider
          colorSpace="hsb"
          channel="alpha"
          isDisabled={isDisabled}
          onChangeEnd={(next) => onChangeEnd?.(out(next.toFormat("hsb")))}
          className={styles.slider()}
        >
          <SliderTrack
            className={styles.track()}
            style={({ defaultStyle }) => ({
              background: `${defaultStyle.background}, ${checker}`,
            })}
          >
            <ColorThumb orientation="horizontal" />
          </SliderTrack>
        </ColorSlider>
      ) : null}

      {showInput || (showEyeDropper && canPipette) ? (
        <div className={styles.row()}>
          {showInput ? (
            <ColorField
              aria-label="Hex"
              value={hex}
              size="sm"
              isDisabled={isDisabled}
              onChange={(next) => {
                if (!next) return;
                const typed = parseColor(next).toFormat("hsb");
                apply(
                  showAlpha
                    ? typed.withChannelValue(
                        "alpha",
                        color.getChannelValue("alpha"),
                      )
                    : typed,
                );
              }}
            />
          ) : null}
          {showEyeDropper && canPipette ? (
            <Button
              isIcon
              variant="outline"
              size="sm"
              aria-label="Pick a color from the screen"
              isDisabled={isDisabled}
              onPress={pipette}
              className="shrink-0"
            >
              <PipetteIcon />
            </Button>
          ) : null}
        </div>
      ) : null}

      {swatches?.length ? (
        // biome-ignore lint/a11y/useSemanticElements: a group of buttons, not a set of form fields
        <div role="group" aria-label="Colors" className={styles.swatches()}>
          {swatches.map((swatch) => {
            const swatchColor = toColor(swatch);
            const isPicked = swatchColor.toString("hex").toLowerCase() === hex;
            return (
              <button
                key={swatch}
                type="button"
                aria-label={swatch}
                aria-pressed={isPicked}
                disabled={isDisabled}
                className={styles.swatch()}
                style={{ background: swatchColor.toString("css") }}
                onClick={() => {
                  const kept = showAlpha
                    ? swatchColor.withChannelValue(
                        "alpha",
                        color.getChannelValue("alpha"),
                      )
                    : swatchColor;
                  apply(kept);
                  onChangeEnd?.(out(kept));
                }}
              />
            );
          })}
        </div>
      ) : null}
    </div>
  );

  const picker = (
    <AriaColorPicker value={color} onChange={apply}>
      {panel}
    </AriaColorPicker>
  );

  if (!isPopover) {
    return (
      // biome-ignore lint/a11y/useSemanticElements: a group of controls that hold one color
      <div
        role="group"
        aria-label={
          ariaLabel ?? (typeof label === "string" ? label : "Color picker")
        }
        className={cn(styles.root(), className)}
      >
        {label ? <span className="text-sm font-medium">{label}</span> : null}
        {picker}
      </div>
    );
  }

  return (
    <div className={cn(styles.root(), "items-start", className)}>
      <DialogTrigger>
        {label ? <Label className="text-sm font-medium">{label}</Label> : null}
        <Button
          variant="outline"
          isDisabled={isDisabled}
          aria-label={
            ariaLabel ??
            (typeof label === "string" ? `${label}, ${hex}` : `Color, ${hex}`)
          }
          className={styles.trigger()}
        >
          <span
            aria-hidden="true"
            className={styles.triggerSwatch()}
            style={{
              background: isOpaque
                ? color.toString("css")
                : `linear-gradient(${color.toString("css")}, ${color.toString("css")}), ${checker}`,
            }}
          />
          <span className={styles.triggerValue()}>{hex}</span>
        </Button>
        <Popover
          placement={placement}
          className={cn(styles.popover(), "w-auto")}
        >
          <Dialog
            aria-label={ariaLabel ?? "Color picker"}
            className="outline-none"
          >
            {picker}
          </Dialog>
        </Popover>
      </DialogTrigger>
    </div>
  );
}

4. Use it

import { ColorPicker } from "@/components/ui/color-picker/color-picker";

Anatomy

An area, one or two sliders, a hex field with an eyedropper, and a row of swatches.

<ColorPicker
  aria-label="Brand color"
  defaultValue="#3b82f6"
  swatches={["#ef4444", "#22c55e", "#3b82f6"]}
  onChange={(color) => console.log(color)} // "#3b82f6"
/>
PartRendered asNotes
AreadivSaturation across, brightness up. The thumb marks the color.
Hue sliderdivA rainbow track with a thumb: the hue of the color.
Opacity sliderdivWith showAlpha: from clear to solid, over a checkerboard.
Hex fieldinputThe hex code, to type or paste, with a swatch of the color.
EyedropperbuttonPicks a color from anywhere on the screen. Only in browsers that have one.
SwatchesbuttonsReady-made colors to pick in one press. The one that matches the color is ringed.

Give the picker an aria-label that says what the color is for, such as "Brand color". It is "Color picker" unless you set it.

Keyboard

Every part can be reached and used without a mouse.

KeyWhat it does
TabMoves through the area, the sliders, the hex field, the eyedropper and the swatches.
Arrow keysIn the area, move the thumb by one step across the two channels. In a slider, move its thumb.
Home, End, Page Up, Page DownIn the area and the sliders, move by a larger step.
Enter or SpaceOn a swatch, pick it. On the eyedropper, open it.
EscapeIn a popover, close it. In the eyedropper, cancel it.

Examples

Usage

Drag in the area and the sliders, type a hex, or press the eyedropper if your browser has one.

Controlled

Keep the color in your own state with value and onChange. Giving it a new color, such as from a button, moves the thumbs and fills the field.

value: #3b82f6

Swatches

swatches lists colors to pick in one press. The one that matches the current color is ringed.

Opacity

showAlpha adds a slider from clear to solid, over a checkerboard, and the color carries its opacity: eight digits in hex, or rgba(...).

value: #3b82f680

In a popover

isPopover shows a button with the color and its hex, and opens the picker in a popover under it. Escape closes it, and focus goes back to the button.

When it is let go

onChange is called all the while a thumb moves, which is many times a second. onChangeEnd is called once, when it is let go or a key press is done, which is the moment to save.

moving: #3b82f6

saved when let go: #3b82f6

Formats

format decides how the color is written when it is given back. Move a thumb in each.

hex: move the thumb

rgb: move the thumb

hsl: move the thumb

hsb: move the thumb

Choosing the parts

Leave out the hex field with showInput={false} and the eyedropper with showEyeDropper={false}, for the smallest picker.

Sizes

Variants

A card with a border and padding, or nothing around it, to sit inside a panel that has its own.

Disabled

Component API

Color Picker takes the props below.

PropTypeDefault
valuestring-
defaultValuestringa blue
onChange(color: string) => void-
onChangeEnd(color: string) => void-
format"hex" | "rgb" | "hsl" | "hsb""hex"
showAlphabooleanfalse
swatchesstring[]-
showInputbooleantrue
showEyeDropperbooleantrue
isPopoverbooleanfalse
labelReactNode-
placement"bottom start" | "bottom end" | "top start" | "top end""bottom start"
size"sm" | "md" | "lg""md"
variant"card" | "plain""card"
isDisabledbooleanfalse
aria-labelstring"Color picker"
classNamestring-