Menu

Components

Color Swatch Picker

A set of colors to pick one from: press a swatch and it is the color.

Introduction

Color Swatch Picker is for choosing from colors you decided on: the color of a label, the accent of a theme, the background of a note. Each color is a swatch, and pressing one picks it. It is lighter than a whole ColorPicker, and it keeps people to the colors that go with your design.

  • Built on react-aria's ColorSwatchPicker: it is one place in the tab order, the arrow keys move between swatches, and a screen reader hears each color and whether it is picked.
  • The colors are strings in CSS, and the color you get back is the string you gave, so it is the same one you keep in your data. Name a color to give the screen reader and the tooltip a word instead of a hex.
  • The picked swatch has a ring and a tick, in black on a light color and in white on a dark one, and a translucent color is drawn over a checkerboard.
  • In a row that wraps, in a grid of fixed columns, or one under the other with the name beside each swatch. Three sizes and three shapes.
  • It works in a form: with a name, the picked color is submitted.

Only the colors you list can be picked, so it cannot hold a color of the user's own. For that, add a ColorPicker or a ColorField beside it. 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 the check icon.

1. Add the styles

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

// Styles for ColorSwatchPicker. The color of each swatch, and the checkerboard
// behind one that is not solid, are set by react-aria as inline styles, so they
// are not here.
export const colorSwatchPickerStyles = tv({
  slots: {
    root: "flex flex-col gap-2",
    label: "text-sm font-medium",
    list: "flex flex-wrap gap-2",
    item: [
      "relative shrink-0 cursor-pointer outline-none transition-transform",
      "hover:scale-110 motion-reduce:transition-none motion-reduce:hover:scale-100",
      "data-focus-visible:ring-2 data-focus-visible:ring-ring data-focus-visible:ring-offset-2 data-focus-visible:ring-offset-bg",
      "data-selected:ring-2 data-selected:ring-fg data-selected:ring-offset-2 data-selected:ring-offset-bg",
    ],
    // The square the swatch is drawn in, and the swatch that fills it.
    box: "relative block shrink-0",
    // The tick on the picked swatch, in the color that reads on it.
    check:
      "pointer-events-none absolute inset-0 m-auto opacity-0 transition-opacity data-[on=true]:opacity-100 motion-reduce:transition-none",
  },
  variants: {
    size: {
      sm: { box: "size-6", check: "size-3.5" },
      md: { box: "size-8", check: "size-4" },
      lg: { box: "size-10", check: "size-5" },
    },
    shape: {
      circle: {
        item: "rounded-full",
        box: "rounded-full",
      },
      rounded: { item: "rounded-lg", box: "rounded-lg" },
      square: {
        item: "rounded-none",
        box: "rounded-none",
      },
    },
    layout: {
      grid: { list: "flex-wrap" },
      // One under the other, with the name beside each swatch.
      stack: {
        list: "flex-col flex-nowrap gap-1",
        item: "flex w-full items-center gap-3 rounded-md pr-3",
      },
    },
  },
  defaultVariants: { size: "md", shape: "circle", layout: "grid" },
});

2. Add the Color Swatch Picker file

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

import { type CSSProperties, type ReactNode, useId, useState } from "react";
import {
  ColorSwatchPicker as AriaColorSwatchPicker,
  type Color,
  ColorSwatchPickerItem,
  parseColor,
} from "react-aria-components";
import { CheckIcon } from "@/components/icons";
import { ColorSwatch } from "@/components/ui/color-swatch/color-swatch";
import { cn } from "@/lib/cn";
import { colorSwatchPickerStyles } from "@/types/color-swatch-picker-styles";

/** A color to offer: any color in CSS, or one with a name. */
export type ColorSwatchOption = string | { value: string; label?: string };

export interface ColorSwatchPickerProps {
  /** The colors to offer, in CSS (`"#3b82f6"`, `"rgb(59, 130, 246)"`, `"hsl(217, 91%, 60%)"`), or `{ value, label }` to name one. */
  colors: ColorSwatchOption[];
  /** The picked color, written as it is in `colors`, or `null` for none. For a controlled picker. */
  value?: string | null;
  /** The color to start with, for an uncontrolled picker. */
  defaultValue?: string | null;
  /** Called with the picked color, written as it is in `colors`. */
  onChange?: (color: string) => void;
  /** A label above the swatches. Without one, name the picker with `aria-label`. */
  label?: ReactNode;
  /** How big the swatches are. Defaults to `md`. */
  size?: "sm" | "md" | "lg";
  /** Round, rounded squares or square. Defaults to `circle`. */
  shape?: "circle" | "rounded" | "square";
  /**
   * In a row that wraps (`grid`), or one under the other with the name of each
   * beside it (`stack`). It also decides how the arrow keys move. Defaults to
   * `grid`.
   */
  layout?: "grid" | "stack";
  /** With `grid`: how many swatches in a row. Without it they fill the width and wrap. */
  columns?: number;
  /** The name of the form field that holds the picked color. */
  name?: string;
  isDisabled?: boolean;
  "aria-label"?: string;
  className?: string;
}

interface Item {
  value: string;
  label: string;
  color: Color;
}

function toItem(option: ColorSwatchOption): Item | null {
  const value = typeof option === "string" ? option : option.value;
  try {
    const color = parseColor(value);
    const label =
      typeof option === "string" || !option.label
        ? color.toString("hex").toLowerCase()
        : option.label;
    return { value, label, color };
  } catch {
    return null;
  }
}

// react-aria has no way to say "nothing is picked" once a picker is controlled,
// so a color that no swatch has stands for it.
const noneColor = parseColor("rgba(1, 2, 3, 0.004)");

const sameColor = (a: Color, b: Color) =>
  a.toString("hexa") === b.toString("hexa");

// The color that reads on top of a swatch: black on a light one, white on a dark
// one, worked out from how bright it looks.
function tickColor(color: Color) {
  const { r, g, b } = {
    r: color.getChannelValue("red"),
    g: color.getChannelValue("green"),
    b: color.getChannelValue("blue"),
  };
  const alpha = color.getChannelValue("alpha");
  // A translucent swatch shows the page behind it, which is light in the theme
  // it is mostly seen in: count what is missing of it as white.
  const mix = (v: number) => v * alpha + 255 * (1 - alpha);
  const brightness = (0.299 * mix(r) + 0.587 * mix(g) + 0.114 * mix(b)) / 255;
  return brightness > 0.6 ? "#000000" : "#ffffff";
}

/**
 * A row of colors to pick one from: press a swatch and it is the color, marked
 * with a ring and a tick. Use it for a set of colors that you chose, such as the
 * colors of a label, a theme accent or a note, where a whole `ColorPicker` would
 * be too much.
 *
 * Built on react-aria's ColorSwatchPicker, so it is one place in the tab order
 * and the arrow keys move between swatches, a screen reader hears each color and
 * whether it is picked, and a color with some transparency is drawn over a
 * checkerboard.
 *
 * The colors are plain strings in CSS, and the color you get back is the string
 * you gave, so it is the same one you keep in your data. Name a color with `{
 * value, label }` to have a name for the screen reader and a tooltip, instead
 * of its hex.
 *
 * @example
 * <ColorSwatchPicker
 *   aria-label="Label color"
 *   colors={["#ef4444", "#22c55e", { value: "#3b82f6", label: "Blue" }]}
 *   onChange={setColor}
 * />
 */
export function ColorSwatchPicker({
  colors,
  value,
  defaultValue,
  onChange,
  label,
  size,
  shape,
  layout = "grid",
  columns,
  name,
  isDisabled,
  "aria-label": ariaLabel,
  className,
}: ColorSwatchPickerProps) {
  const styles = colorSwatchPickerStyles({ size, shape, layout });
  const labelId = useId();
  const items = colors
    .map(toItem)
    .filter((item): item is Item => item !== null);
  // The picked color as text, kept here so a form field can carry it too.
  const [picked, setPicked] = useState<string | null>(
    value !== undefined ? value : (defaultValue ?? null),
  );
  if (value !== undefined && value !== picked) setPicked(value);

  const pickedColor = (() => {
    if (picked === null) return null;
    try {
      return parseColor(picked);
    } catch {
      return null;
    }
  })();
  const current = pickedColor
    ? items.find((item) => sameColor(item.color, pickedColor))
    : undefined;

  const listStyle: CSSProperties | undefined =
    layout === "grid" && columns
      ? {
          display: "grid",
          gridTemplateColumns: `repeat(${columns}, max-content)`,
        }
      : undefined;

  return (
    <div className={cn(styles.root(), className)}>
      {label ? (
        <span id={labelId} className={styles.label()}>
          {label}
        </span>
      ) : null}
      {/* Nothing can be reached or pressed while it is disabled: react-aria has no disabled state for it, so the whole set is made inert. */}
      <div
        inert={isDisabled}
        aria-disabled={isDisabled || undefined}
        className={cn(isDisabled && "cursor-not-allowed opacity-50")}
      >
        <AriaColorSwatchPicker
          layout={layout}
          aria-label={label ? undefined : (ariaLabel ?? "Colors")}
          aria-labelledby={label ? labelId : undefined}
          value={pickedColor ?? noneColor}
          onChange={(next) => {
            const item = items.find((entry) => sameColor(entry.color, next));
            if (!item) return;
            setPicked(item.value);
            onChange?.(item.value);
          }}
          className={cn(
            styles.list(),
            isDisabled && "cursor-not-allowed opacity-50",
          )}
          style={listStyle}
        >
          {items.map((item, i) => {
            const isPicked = current === item;
            return (
              <ColorSwatchPickerItem
                // biome-ignore lint/suspicious/noArrayIndexKey: two options can be the same color
                key={i}
                color={item.color}
                aria-label={item.label}
                className={styles.item()}
              >
                <span className={styles.box()} title={item.label}>
                  <ColorSwatch size="fill" shape={shape ?? "circle"} />
                  <CheckIcon
                    data-on={isPicked}
                    className={styles.check()}
                    style={{ color: tickColor(item.color) }}
                  />
                </span>
                {layout === "stack" ? (
                  <span className="text-sm">{item.label}</span>
                ) : null}
              </ColorSwatchPickerItem>
            );
          })}
        </AriaColorSwatchPicker>
      </div>
      {name ? <input type="hidden" name={name} value={picked ?? ""} /> : null}
    </div>
  );
}

3. Use it

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

Anatomy

A label and a set of swatches, one of them marked.

<ColorSwatchPicker
  aria-label="Label color"
  colors={["#ef4444", "#22c55e", { value: "#3b82f6", label: "Blue" }]}
  defaultValue="#22c55e"
  onChange={(color) => console.log(color)} // "#22c55e"
/>
PartRendered asNotes
LabelspanNames the picker, above the swatches. Without one, use aria-label.
Swatchdiv (option)One per color. It is one control: press it to pick the color.
TicksvgOn the picked swatch, in black on a light color and in white on a dark one.
Ring-Around the picked swatch, and around the one with the keyboard focus.

Value

The colors are strings in CSS, and you get back the one you gave.

// The colors are strings in CSS, and the color you get back is the string you gave
colors={["#3b82f6", "rgb(34, 197, 94)", "hsl(0, 84%, 60%)"]}
onChange={(color) => ...}   // "rgb(34, 197, 94)"

// Name a color for the screen reader and the tooltip
colors={[{ value: "#3b82f6", label: "Blue" }]}

Keyboard

The swatches are one place in the tab order, and the keys move inside it.

KeyWhat it does
TabMoves to the swatches, on the one that is picked, or the first.
Arrow Left, Arrow RightIn a grid, move to the next or the previous swatch.
Arrow Up, Arrow DownIn a grid, move to the swatch above or below. In a stack, to the previous or the next.
Enter, SpacePick the swatch that has focus.

Examples

Usage

Press a swatch, or focus the picker and use the arrow keys.

Controlled

Keep the color in your own state with value and onChange. null means nothing is picked.

Label color
#3b82f6

Named colors

Give a color a label, and the screen reader and the tooltip say it instead of the hex.

Stacked

layout="stack" puts the swatches one under the other with the name of each beside it, which is easier to read for a few colors. The arrow keys move up and down.

Accent
Red
Orange
Yellow
Green
Blue
Purple

picked: #22c55e

Columns

columns sets how many swatches there are in a row, so they line up in a grid.

Shapes

Sizes

24, 32 and 40 pixels. Large is easier to press on a touch screen.

Translucent colors

A color with some transparency is drawn over a checkerboard, so it can be told from a solid one.

Light and dark colors

The tick and the ring read on white as well as on black.

In a form

With a name, the picked color is submitted as you wrote it.

Label color

Not submitted yet.

Disabled

Component API

Color Swatch Picker takes the props below.

PropTypeDefault
colors(string | { value, label? })[]-
valuestring | null-
defaultValuestring | null-
onChange(color: string) => void-
labelReactNode-
size"sm" | "md" | "lg""md"
shape"circle" | "rounded" | "square""circle"
layout"grid" | "stack""grid"
columnsnumber- (wraps)
namestring-
isDisabledbooleanfalse
aria-labelstring"Colors" (when there is no label)
classNamestring-