Components
Color Slider
A slider for one channel of a color, its track painted with the colors the thumb can reach.
Introduction
Color Slider changes one channel of a color, such as the hue or the opacity, and paints its track with what that would do: a rainbow for the hue, from gray to the pure color for the saturation, from clear to solid for the opacity. So you see the result before you move.
- Built on react-aria's ColorSlider: mouse, touch and keyboard all work, and a screen reader hears the channel and its value.
- Any channel of
hsb,hslorrgb, and the opacity. The other channels do not change while you move one. - The color is a plain string in CSS, such as
"#3b82f6", and the whole color goes back as hex, rgb, hsl or hsb, with its opacity when it has one. - Sliders that share one color through a string should give it back as
hsborhsl, which carry every channel: a hex loses the hue of a black or a gray. - Lying along the width or standing up, three thicknesses, an optional label and value, and a thumb that stays visible on any color.
Use it next to a ColorArea to set the hue, or for the opacity. For a whole picker in one, see ColorPicker. 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 clsxManual installation
Copy these files into your project and keep the paths, or adjust the imports.
1. Add the styles
src/types/color-slider-styles.tsShow code
import { tv } from "tailwind-variants";
// Styles for ColorSlider. The gradient of the track and the place of the thumb
// are set by react-aria from the color as inline styles, so they are not here:
// only sizes, corners, the thumb and the focus ring are.
export const colorSliderStyles = tv({
slots: {
root: "group/color-slider flex flex-col gap-2 text-fg",
header: "flex items-center justify-between gap-3 text-sm",
label: "font-medium",
output: "font-mono text-xs text-muted-fg tabular-nums",
track:
"relative rounded-full data-disabled:cursor-not-allowed data-disabled:opacity-60",
},
variants: {
orientation: {
horizontal: { root: "w-full", track: "w-full" },
// A tall track, with the label and the value above it.
vertical: { root: "h-full w-fit items-center", track: "h-48" },
},
size: {
sm: {},
md: {},
lg: {},
},
},
compoundVariants: [
{ orientation: "horizontal", size: "sm", class: { track: "h-2.5" } },
{ orientation: "horizontal", size: "md", class: { track: "h-4" } },
{ orientation: "horizontal", size: "lg", class: { track: "h-6" } },
{ orientation: "vertical", size: "sm", class: { track: "w-2.5" } },
{ orientation: "vertical", size: "md", class: { track: "w-4" } },
{ orientation: "vertical", size: "lg", class: { track: "w-6" } },
],
defaultVariants: { orientation: "horizontal", size: "md" },
});2. Add the Color Slider file
src/components/ui/color-slider/color-slider.tsxShow code
"use client";
import { type ReactNode, useState } from "react";
import {
ColorSlider as AriaColorSlider,
type Color,
type ColorChannel,
Label,
parseColor,
SliderOutput,
SliderTrack,
} from "react-aria-components";
import { ColorThumb } from "@/components/ui/color-thumb/color-thumb";
import { cn } from "@/lib/cn";
import { colorSliderStyles } from "@/types/color-slider-styles";
/** The color spaces a slider can move through. */
export type ColorSliderSpace = "hsb" | "hsl" | "rgb";
/** How the color is written when it is given back. */
export type ColorSliderFormat = "hex" | "rgb" | "hsl" | "hsb";
export interface ColorSliderProps {
/** The color, written in CSS: `"#3b82f6"`, `"rgb(59, 130, 246)"`, `"hsl(217, 91%, 60%)"` or `"hsb(217, 76%, 96%)"`. For a controlled slider. */
value?: string;
/** The color to start with, for an uncontrolled slider. */
defaultValue?: string;
/** Called as the thumb moves, with the whole 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;
/**
* Which channel of the color the slider changes: `hue`, `saturation`,
* `brightness` or `lightness` in `hsb` and `hsl`, `red`, `green` or `blue` in
* `rgb`, and `alpha` (the opacity) in all of them. Defaults to `hue`.
*/
channel?: ColorChannel;
/** The color space of the channel. The other channels stay where they are. Defaults to `hsb`. */
colorSpace?: ColorSliderSpace;
/** How the color is written when it is given back. It carries its opacity when the color is not solid. Defaults to `hex`. */
format?: ColorSliderFormat;
/** A label above the track, at the left. Without one, name the slider with `aria-label`. */
label?: ReactNode;
/** The number of the channel, such as 217° or 76%, above the track, at the right. Defaults to `false`. */
showValue?: boolean;
/** Lie along the width, or stand up. Defaults to `horizontal`. */
orientation?: "horizontal" | "vertical";
/** How thick the track is. Defaults to `md`. */
size?: "sm" | "md" | "lg";
/** The name of the form field that holds the number of the channel. */
name?: string;
isDisabled?: boolean;
"aria-label"?: string;
className?: string;
}
const fallback = "hsb(220, 80%, 90%)";
function toColor(text: string | undefined, space: ColorSliderSpace): Color {
try {
return parseColor(text ?? fallback).toFormat(space);
} catch {
return parseColor(fallback).toFormat(space);
}
}
// Written in lower case, as CSS is usually written, and with the opacity when
// there is one to keep.
const write = (color: Color, format: ColorSliderFormat, keepAlpha: boolean) => {
const alpha = keepAlpha || color.getChannelValue("alpha") < 1;
const text = color.toString(alpha ? (`${format}a` as const) : format);
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";
/**
* A slider for one channel of a color, its track painted with the colors the
* thumb can reach: the hue as a rainbow, the saturation from gray to the pure
* color, the opacity from clear to solid over a checkerboard. Use one for each
* channel you want to tune, next to a `ColorArea` or on its own.
*
* Built on react-aria's ColorSlider, 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), and a screen reader hears the channel and its value.
*
* The color is a plain string in CSS and goes back as hex unless you choose
* another `format`. The other channels do not change while you move one, and a
* hue that hex loses when the color is gray or black is kept in the slider.
* Sliders that share one color through a string should give it back as `hsb`
* or `hsl`, which carry every channel.
*
* @example
* <ColorSlider label="Hue" showValue defaultValue="#3b82f6" onChange={setColor} />
*/
export function ColorSlider({
value,
defaultValue,
onChange,
onChangeEnd,
channel = "hue",
colorSpace = "hsb",
format = "hex",
label,
showValue = false,
orientation,
size,
name,
isDisabled,
"aria-label": ariaLabel,
className,
}: ColorSliderProps) {
const styles = colorSliderStyles({ orientation, size });
const [color, setColor] = useState<Color>(() =>
toColor(value ?? defaultValue, colorSpace),
);
// A controlled slider 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. Two colors are the same when every channel of the space matches,
// because two can share a hex and differ in a hue that hex loses.
if (value !== undefined) {
const next = toColor(value, colorSpace);
const form = `${colorSpace}a` as const;
if (next.toString(form) !== color.toString(form)) setColor(next);
}
const isAlpha = channel === "alpha";
const hasHeader = Boolean(label) || showValue;
return (
<AriaColorSlider
value={color}
channel={channel}
colorSpace={colorSpace}
orientation={orientation}
name={name}
isDisabled={isDisabled}
aria-label={label ? undefined : (ariaLabel ?? channel)}
onChange={(next) => {
setColor(next);
onChange?.(write(next, format, isAlpha));
}}
onChangeEnd={(next) => onChangeEnd?.(write(next, format, isAlpha))}
className={cn(styles.root(), className)}
>
{hasHeader ? (
<div className={styles.header()}>
{label ? <Label className={styles.label()}>{label}</Label> : <span />}
{showValue ? <SliderOutput className={styles.output()} /> : null}
</div>
) : null}
<SliderTrack
className={styles.track()}
style={({ defaultStyle }) =>
isAlpha
? { background: `${defaultStyle.background}, ${checker}` }
: defaultStyle
}
>
<ColorThumb orientation={orientation ?? "horizontal"} />
</SliderTrack>
</AriaColorSlider>
);
}3. Use it
import { ColorSlider } from "@/components/ui/color-slider/color-slider";Anatomy
A track with a thumb on it, and an optional label and value above.
<ColorSlider
label="Hue"
showValue
defaultValue="#3b82f6"
onChange={(color) => console.log(color)} // "#3b82f6"
/>| Part | Rendered as | Notes |
|---|---|---|
| Label | label | Names the slider, at the left above the track. Without one, use aria-label. |
| Value | output | The number of the channel, such as 217° or 76%, at the right above the track. Off unless showValue. |
| Track | div | Painted with the colors the thumb can reach, so it always shows what the slider will do. |
| Thumb | div | The round handle. It grows a little while it is dragged or focused, and has a dark and a light edge to show on any color. |
Value
The color is text in CSS. The whole color goes back, in the format you choose.
// Any color in CSS. The whole color goes back, in the format you choose (hex by default).
"#3b82f6"
"rgb(59, 130, 246)"
"hsl(217, 91%, 60%)"
"hsb(217, 76%, 96%)"
// A color that is not solid keeps its opacity
"#3b82f680"Channels
channel chooses what the slider changes, and colorSpace the space it belongs to.
| channel | colorSpace | The track |
|---|---|---|
| hue | hsb, hsl | 0 to 360, as a rainbow |
| saturation | hsb, hsl | From gray to the pure color, at the brightness now |
| brightness | hsb | From black to the color |
| lightness | hsl | From black through the color to white |
| red, green, blue | rgb | 0 to 255 of that primary, the other two kept |
| alpha | any | The opacity, from clear to solid, over a checkerboard |
Keyboard
The slider is one place in the tab order. These keys work while it has focus.
| Key | What it does |
|---|---|
| Arrow Left, Arrow Right | Move the thumb by one step (up and down in a vertical slider). |
| Arrow Up, Arrow Down | Move the thumb by one step. |
| Page Up, Page Down | Move by a larger step. |
| Home, End | Move to the start or the end of the track. |
Examples
Usage
Drag the thumb, or focus the slider and use the arrow keys. It is a hue slider unless you choose another channel.
Label and value
label goes above the track at the left, and showValue writes the number of the channel at the right.
Hue, saturation and brightness
One slider for each channel of the same color, with the color given back as hsb so that every channel is kept.
value: hsb(217, 76%, 96%)
Hue, saturation and lightness
In hsl the saturation slider goes from gray to the pure color, and the lightness slider from black through the color to white.
Red, green and blue
In rgb each track runs from 0 to 255 of that primary, with the other two kept.
value: #3b82f6
Opacity
The alpha channel runs from clear to solid over a checkerboard, and the color carries its opacity: eight digits in hex.
value: #3b82f680
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
Formats
format decides how the whole color is written when it is given back: hex, rgb, hsl or hsb.
move the thumb
move the thumb
move the thumb
move the thumb
Sizes
Vertical
orientation vertical stands the slider up, with the label and the value above it. Give it a height with className if 12 rem is not right.
In a form
Name the slider with name, and the number of the channel is submitted, such as 217 for a hue.
Disabled
Component API
Color Slider takes the props below.
| Prop | Type | Default |
|---|---|---|
| value | string | - |
| defaultValue | string | a blue |
| onChange | (color: string) => void | - |
| onChangeEnd | (color: string) => void | - |
| channel | ColorChannel | "hue" |
| colorSpace | "hsb" | "hsl" | "rgb" | "hsb" |
| format | "hex" | "rgb" | "hsl" | "hsb" | "hex" |
| label | ReactNode | - |
| showValue | boolean | false |
| orientation | "horizontal" | "vertical" | "horizontal" |
| size | "sm" | "md" | "lg" | "md" |
| name | string | - |
| isDisabled | boolean | false |
| aria-label | string | the channel (when there is no label) |
| className | string | - |