Menu

Components

Color Area

A square to pick a color from: move the thumb across two channels of a color space, such as saturation and brightness.

Introduction

Color Area is the square of a color picker: drag a thumb across it and the color changes along two channels at once. In the usual hsb space, moving right adds saturation and moving up adds brightness, so the corners are white, black and the pure color.

  • Built on react-aria's ColorArea: mouse, touch and keyboard all work, a screen reader hears both channels and their values, and the two values can be sent in a form.
  • It moves through hsb, hsl or rgb, and you can choose which two channels the thumb moves across. The third stays where it is.
  • The color is a plain string in CSS, such as "#3b82f6", and goes back as hex, rgb, hsl or hsb.
  • The hue that a hex color loses when it is gray or black is kept in the area, so the thumb does not jump when the color it gave comes back to it.
  • Four sizes, a square or a wide shape, an optional swatch and value under it, and a thumb that stays visible on any color.

The area picks two channels of a color. The third, most often the hue, is the one of the color it starts from: to change it, give the area a new color, or put a separate control for it next to the area. 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.

1. Add the styles

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

// Styles for ColorArea. The gradient of the area and the place of the thumb are
// set by react-aria from the color, as inline styles, so they are not here: only
// the size, the corners, the thumb and the focus ring are.
export const colorAreaStyles = tv({
  slots: {
    root: "inline-flex max-w-full flex-col gap-2",
    area: [
      "relative 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",
    ],
    caption: "flex items-center gap-2 text-sm",
    swatch: "size-4 shrink-0 rounded border",
    value: "font-mono text-xs text-muted-fg tabular-nums",
  },
  variants: {
    size: {
      sm: { area: "h-40 w-40" },
      md: { area: "h-52 w-52" },
      lg: { area: "h-64 w-64" },
      // As wide as its parent, and as tall as `shape` makes it.
      full: { root: "flex w-full", area: "w-full" },
    },
    shape: {
      square: {},
      wide: {},
    },
  },
  compoundVariants: [
    { size: "full", shape: "square", class: { area: "aspect-square" } },
    { size: "full", shape: "wide", class: { area: "aspect-[2/1]" } },
    {
      size: ["sm", "md", "lg"],
      shape: "wide",
      class: { area: "h-auto aspect-[2/1]" },
    },
    { size: "sm", shape: "wide", class: { area: "w-56" } },
    { size: "md", shape: "wide", class: { area: "w-72" } },
    { size: "lg", shape: "wide", class: { area: "w-96" } },
  ],
  defaultVariants: { size: "md", shape: "square" },
});

2. Add the Color Area file

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

import { useState } from "react";
import {
  ColorArea as AriaColorArea,
  type Color,
  type ColorChannel,
  parseColor,
} from "react-aria-components";
import { ColorThumb } from "@/components/ui/color-thumb/color-thumb";
import { cn } from "@/lib/cn";
import { colorAreaStyles } from "@/types/color-area-styles";

/** The color spaces an area can move through. */
export type ColorAreaSpace = "hsb" | "hsl" | "rgb";

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

export interface ColorAreaProps {
  /** The color, written in CSS: `"#3b82f6"`, `"rgb(59, 130, 246)"`, `"hsl(217, 91%, 60%)"` or `"hsb(217, 76%, 96%)"`. For a controlled area. */
  value?: string;
  /** The color to start with, for an uncontrolled area. */
  defaultValue?: string;
  /** Called as the thumb moves, with the color 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;
  /**
   * The color space the two channels belong to. The thumb moves across two of
   * its channels, and the third stays where it is. Defaults to `hsb`.
   */
  colorSpace?: ColorAreaSpace;
  /**
   * The channel along the bottom. In `hsb` and `hsl` it is `saturation`, `hue`
   * or the last one; in `rgb` it is `red`, `green` or `blue`. Defaults to the
   * saturation, or the red.
   */
  xChannel?: ColorChannel;
  /** The channel up the side. Defaults to the brightness or the lightness, or the green. */
  yChannel?: ColorChannel;
  /** How the color is written when it is given back, and shown. Defaults to `hex`. */
  format?: ColorAreaFormat;
  /** How big it is. `full` fills the width of its parent. Defaults to `md`. */
  size?: "sm" | "md" | "lg" | "full";
  /** Square, or twice as wide as tall. Defaults to `square`. */
  shape?: "square" | "wide";
  /** A swatch of the color and its value under the area. Defaults to `false`. */
  showValue?: boolean;
  /** The name of the form field that holds the value along the bottom, sent as a number. */
  xName?: string;
  /** The name of the form field that holds the value up the side. */
  yName?: string;
  isDisabled?: boolean;
  /** Names the area for screen readers, such as "Color". */
  "aria-label"?: string;
  className?: string;
}

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

const defaultChannels: Record<ColorAreaSpace, [ColorChannel, ColorChannel]> = {
  hsb: ["saturation", "brightness"],
  hsl: ["saturation", "lightness"],
  rgb: ["red", "green"],
};

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

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

/**
 * A square to pick a color from: the thumb moves across two channels of a color
 * space, and the area is painted with the colors it can reach. In the default
 * `hsb` space it is the familiar picker with saturation along the bottom and
 * brightness up the side, and the hue kept by the color it starts from, which
 * you change with a control of its own, or by giving the area a new color.
 *
 * Built on react-aria's ColorArea, so it works with a mouse, a finger and the
 * keyboard (the arrow keys move the thumb by one, and Page Up and Page Down,
 * Home and End by more), a screen reader hears the two channels and their
 * values, and it can be part of a form.
 *
 * The color is a plain string in CSS, so it can come from a form, a database or
 * a theme, and goes back as hex unless you choose another `format`. The hue,
 * which a hex color loses when it is gray or black, is kept in the area
 * itself.
 *
 * @example
 * <ColorArea aria-label="Color" defaultValue="#3b82f6" onChange={setColor} />
 */
export function ColorArea({
  value,
  defaultValue,
  onChange,
  onChangeEnd,
  colorSpace = "hsb",
  xChannel,
  yChannel,
  format = "hex",
  size,
  shape,
  showValue = false,
  xName,
  yName,
  isDisabled,
  "aria-label": ariaLabel = "Color",
  className,
}: ColorAreaProps) {
  const styles = colorAreaStyles({ size, shape });
  const [defaultX, defaultY] = defaultChannels[colorSpace];
  const [color, setColor] = useState<Color>(() =>
    toColor(value ?? defaultValue, colorSpace),
  );

  // A controlled area 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, colorSpace);
    if (next.toString("hex") !== color.toString("hex")) setColor(next);
  }

  const shown = write(color, format);

  return (
    <div className={cn(styles.root(), className)}>
      <AriaColorArea
        aria-label={ariaLabel}
        value={color}
        colorSpace={colorSpace}
        xChannel={xChannel ?? defaultX}
        yChannel={yChannel ?? defaultY}
        xName={xName}
        yName={yName}
        isDisabled={isDisabled}
        onChange={(next) => {
          setColor(next);
          onChange?.(write(next, format));
        }}
        onChangeEnd={(next) => onChangeEnd?.(write(next, format))}
        className={styles.area()}
      >
        <ColorThumb />
      </AriaColorArea>
      {showValue ? (
        <div className={styles.caption()}>
          <span
            aria-hidden="true"
            className={styles.swatch()}
            style={{ background: color.toString("css") }}
          />
          <output className={styles.value()}>{shown}</output>
        </div>
      ) : null}
    </div>
  );
}

3. Use it

import { ColorArea } from "@/components/ui/color-area/color-area";

Anatomy

A painted area with a thumb on it, and an optional value under it.

<ColorArea
  aria-label="Brand color"
  defaultValue="#3b82f6"
  onChange={(color) => console.log(color)} // "#3b82f6"
  showValue
/>
PartRendered asNotes
AreadivA rectangle painted with the colors the thumb can reach. It is one control with two values, one along the bottom and one up the side.
ThumbdivThe round handle that marks the color. It grows a little while it is dragged or focused, and has a dark and a light edge to show on any color.
ValueoutputA swatch and the color as text, under the area. Off unless showValue.

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

Value

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

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

Keyboard

The area is one place in the tab order. These keys work while it has focus.

KeyWhat it does
Arrow Left, Arrow RightMove along the bottom channel by one step.
Arrow Up, Arrow DownMove up the side channel by one step.
Home, EndMove the bottom channel by a larger step, down or up.
Page Up, Page DownMove the side channel by a larger step, up or down.

Examples

Usage

Drag the thumb, or focus the area and use the arrow keys.

#3b82f6

Controlled

Keep the color in your own state with value and onChange. Giving it a new color, such as from one of the buttons, moves the thumb.

#3b82f6

When it is let go

onChange is called all the while the 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

Color spaces

The space decides which channels there are. In hsb the area has saturation across and brightness up, in hsl saturation and lightness, and in rgb red and green with the blue kept.

Other channels

xChannel and yChannel choose the two channels the thumb moves across. Hue across and saturation up makes a rainbow that fades to gray, at the brightness of the color.

Formats

format decides how the color is written when it is given back and shown: hex, rgb, hsl or hsb. Move the thumb of any of them.

hex

#3b82f6

rgb

rgb(59, 130, 246)

hsl

hsl(217.22, 91.22%, 59.8%)

hsb

hsb(217.22, 76.02%, 96.47%)

Sizes

Small, medium and large are 160, 208 and 256 pixels wide. full fills the width of its parent.

Shapes

Square, or twice as wide as tall, which suits a small place.

Showing the value

showValue adds a swatch of the color and its value, in the format you chose, under the area.

#ef4444

In a form

Name the two channels with xName and yName, and each value is submitted as a number of its own.

Not submitted yet.

Disabled

Component API

Color Area takes the props below.

PropTypeDefault
valuestring-
defaultValuestringa blue
onChange(color: string) => void-
onChangeEnd(color: string) => void-
colorSpace"hsb" | "hsl" | "rgb""hsb"
xChannelColorChannelsaturation, or red in rgb
yChannelColorChannelbrightness, lightness, or green in rgb
format"hex" | "rgb" | "hsl" | "hsb""hex"
size"sm" | "md" | "lg" | "full""md"
shape"square" | "wide""square"
showValuebooleanfalse
xNamestring-
yNamestring-
isDisabledbooleanfalse
aria-labelstring"Color"
classNamestring-