Color Opacity Field
A color and its opacity as one control: a swatch, a hex field and a percentage.
import { ColorOpacityField, ColorOpacityValue } from '@youj/react'
Installation & usage
npm i @youj/reactFor an app already set up with npx @youj/cli init, which installs the peers (@youj/core, @youj/motion, motion and Base UI) and wires the provider. New app? Start at Installation.
Use it where a color comes with an alpha, as in a shadow, a stroke or a fill. For a color alone, use a Color Picker.
import { useState } from 'react'
import { ColorOpacityField, type ColorOpacityValue } from '@youj/react'
export function Fill() {
const [fill, setFill] = useState<ColorOpacityValue>({ color: '#4c6fff', opacity: 80 })
return <ColorOpacityField value={fill} onValueChange={setFill} aria-label="Fill" />
}The value is { color, opacity }: color is #rrggbb and opacity runs from 0 to 100. The hex field reads 3, 4, 6 and 8 digits, with or without the #: f80, #ff8800, ff880080. The 4- and 8-digit forms carry an alpha, which sets the opacity. A paste that parses is applied at once; typed text commits on Enter or blur, is marked invalid while it isn't a color, and is put back on blur or Escape.
Description
A fill color with its opacity, and the color it makes below.
The swatch opens a Color Picker in a popover. The hex field shows six digits without the #; paste or type what you have. The percentage next to it is a Scrub Number Field: drag its drop, type a value, or use the arrow keys.
Code
color-opacity-field-demo.tsx, the Demo story. The component itself comes from the package.
Reference
Propsvalue, defaultValue, onValueChange, size, disabled…
Props
| Prop | Type | |
|---|---|---|
value | ColorOpacityValue | – |
defaultValue | ColorOpacityValuedefault { color: '#000000', opacity: 100 } | { color: '#000000', opacity: 100 } |
onValueChange | (value: ColorOpacityValue) => void | – |
size | 'sm' | 'default'
default 'default' | 'default' |
disabled | boolean | – |
aria-label | stringNames the whole group. default 'Color' | 'Color' |
id | string | – |
className | string | – |
AccessibilityGroup, names, keyboard
Accessibility
- The control is a
groupnamed byaria-label(default "Color"). Inside it, the swatch button says "Color, #4c6fff", the hex field is "Hex color" and the percentage is "Opacity". - The hex field is a text field: Enter commits, Escape reverts, and invalid text sets
aria-invalid. - The opacity is a spinbutton with the keys of a Scrub Number Field.
- The popover is the Color Picker's, so it keeps its keyboard support and becomes a sheet on touch.