Skip to content

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/react

For 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.

Reference

Propsvalue, defaultValue, onValueChange, size, disabled…

Props

ColorOpacityField props
PropType
valueColorOpacityValue–
defaultValueColorOpacityValue

default { color: '#000000', opacity: 100 }

{ color: '#000000', opacity: 100 }
onValueChange(value: ColorOpacityValue) => void–
size'sm' | 'default'

sm fits a dense panel.

default 'default'

'default'
disabledboolean–
aria-labelstring

Names the whole group.

default 'Color'

'Color'
idstring–
classNamestring–
AccessibilityGroup, names, keyboard

Accessibility

  • The control is a group named by aria-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.