ColorPicker
A field for picking a color as #rrggbb, with hue, saturation and lightness sliders and swatches.
Import
import { ColorPicker } from '@k8ordo/ui';Usage
name goes on a text input. A color picked with the sliders or a swatch is written into it, and an input event fires. Pressing the color chip beside the input opens the browser’s own color picker, and a color chosen there goes into the input the same way. While typing, the text counts as a color only once it has six digits. On blur and on Enter it is tidied to lowercase #rrggbb, and a three-digit #f80 is expanded.
<ColorPicker aria-label="Accent color" defaultValue="#0d9488" name="accent" />Swatches
Each swatch is a toggle button named by its label. The one matching the current color is pressed.
const swatches = [
{ value: '#0d9488', label: 'Teal' },
{ value: '#2563eb', label: 'Blue' },
{ value: '#f97316', label: 'Orange' },
{ value: '#e11d48', label: 'Rose' },
{ value: '#171717', label: 'Black' },
];
<ColorPicker
aria-label="Accent color"
defaultValue="#f97316"
swatches={swatches}
/>Controlled
onChange receives #rrggbb, or '' when the field is emptied.
value: #2563eb
const [color, setColor] = useState('#2563eb');
<ColorPicker
aria-label="Accent color"
onChange={setColor}
swatches={swatches}
value={color}
/>Disabled
<ColorPicker aria-label="Accent color" defaultValue="#0d9488" disabled />With @k8ordo/form
Spread the input that formFields derives as it is. A .regex() in the schema arrives as pattern and replaces the built-in #[0-9a-fA-F]{6}. Dirty state, rules, clearing an error and reset all work as they are.
// schema.ts
export const themeSchema = z.object({
accent: z.string().regex(/^#[0-9a-f]{6}$/),
});
// theme-form.tsx
const accent = form.field('accent');
<FormControl
errorText={accent.error}
invalid={accent.invalid}
label="Accent color"
required={accent.required}
renderInput={(props) => <ColorPicker {...props} {...accent.input} />}
/>Props
defaultValue?- Type:
string - Default: -
invalid?- Type:
boolean - Default:
false onChange?- Type:
(value: string) => void - Default: -
ref?- Type:
Ref<HTMLInputElement> - Default: -
swatches?- Type:
readonly ColorPickerSwatch[] - Default: -
type?- Type:
string - Default: -
value?- Type:
string - Default: -
| Prop | Type | Default |
|---|---|---|
defaultValue? | string | - |
invalid? | boolean | false |
onChange? | (value: string) => void | - |
ref? | Ref<HTMLInputElement> | - |
swatches? | readonly ColorPickerSwatch[] | - |
type? | string | - |
value? | string | - |
Inherited attributes (except the ones set internally): InputHTMLAttributes<HTMLInputElement>
The wording this component draws (labels, placeholders, and so on) comes from the message dictionary unless a prop sets it. To replace it, see: i18n