Color Picker
ReviewedAn app-ready color field with a swatch activator, popover picker, synchronized HEX and RGB inputs, and reusable preset colors.
Contributed by Trung Nguyễn Quang
Preview
Code
Example.jsx
import { useState } from 'react';
import { BlockStack, Box, Card, ColorPicker, Divider, InlineGrid, InlineStack, Popover, Text, TextField, UnstyledButton, hsbToHex, rgbToHsb } from '@shopify/polaris';
const COLOR_PRESETS = ['#D0021B', '#F5A623', '#F8E71C', '#8B572A', '#7ED321', '#417505', '#BD10E0', '#9013FE', '#4A90E2', '#50E3C2', '#B8E986', '#000000', '#4A4A4A', '#9B9B9B', '#FFFFFF'];
const HEX_PATTERN = /^#[0-9a-f]{6}$/i;
const COLOR_FIELDS = [
{ label: 'Text color', initial: '#1A1A1A' },
{ label: 'Highlight color', initial: '#4A90E2' },
{ label: 'Background color', initial: '#F7F7F7' },
];
const normalizeHex = (value) => {
const trimmed = value.trim();
const withHash = trimmed.startsWith('#') ? trimmed : `#${trimmed}`;
return HEX_PATTERN.test(withHash) ? withHash.toUpperCase() : null;
};
const hexToColorRgb = (hex) => ({
red: parseInt(hex.slice(1, 3), 16),
green: parseInt(hex.slice(3, 5), 16),
blue: parseInt(hex.slice(5, 7), 16),
alpha: 1,
});
const toPickerColor = (hex) => rgbToHsb(hexToColorRgb(hex));
const toDisplayColor = (hex) => {
const { red, green, blue } = hexToColorRgb(hex);
return { hex, red, green, blue };
};
const SWATCH_STYLE = {
width: 24,
height: 24,
borderRadius: '50%',
border: '1px solid var(--p-color-border, #c9cccf)',
boxShadow: 'inset 0 0 0 1px rgba(0, 0, 0, 0.08)',
};
const ColorPickerCard = ({ label, initial }) => {
const [color, setColor] = useState(initial);
const [inputValue, setInputValue] = useState(initial);
const [display, setDisplay] = useState(() => toDisplayColor(initial));
const [pickerColor, setPickerColor] = useState(() => toPickerColor(initial));
const [active, setActive] = useState(false);
const commit = (value) => {
const hex = normalizeHex(value);
if (!hex) return false;
setColor(hex);
setInputValue(hex);
setDisplay(toDisplayColor(hex));
setPickerColor(toPickerColor(hex));
return true;
};
const handlePickerChange = (next) => {
const hex = hsbToHex(next).toUpperCase();
setPickerColor(next);
setColor(hex);
setInputValue(hex);
setDisplay(toDisplayColor(hex));
};
const handleRgbChange = (channel, raw) => {
const value = Math.max(0, Math.min(255, Number(raw) || 0));
const next = { ...display, [channel]: value };
const hex = hsbToHex(rgbToHsb({ red: next.red, green: next.green, blue: next.blue, alpha: 1 })).toUpperCase();
setDisplay({ ...next, hex });
setColor(hex);
setInputValue(hex);
setPickerColor(toPickerColor(hex));
};
const activator = (
<TextField
label="Color"
labelHidden
autoComplete="off"
spellCheck={false}
value={inputValue}
prefix={<div aria-hidden="true" style={{ ...SWATCH_STYLE, width: 16, height: 16, margin: '0 4px 0 2px', background: color }} />}
onFocus={() => setActive(true)}
onChange={(value) => {
setInputValue(value);
commit(value);
}}
onBlur={() => {
if (!commit(inputValue)) setInputValue(color);
}}
/>
);
return (
<Card>
<BlockStack gap="300">
<BlockStack gap="100">
<Text as="h2" variant="headingSm">{label}</Text>
<Text as="p" variant="bodySm" tone="subdued">{color}</Text>
</BlockStack>
<Popover active={active} activator={activator} onClose={() => setActive(false)} preferInputActivator preventFocusOnClose autofocusTarget="none">
<Box width="320px" paddingBlock="300">
<BlockStack gap="300">
<Box paddingInline="300">
<BlockStack gap="200">
<ColorPicker fullWidth color={pickerColor} onChange={handlePickerChange} />
<InlineGrid gap="400" columns="40px auto" alignItems="center">
<Text as="span">HEX</Text>
<TextField
label="Hex"
labelHidden
autoComplete="off"
value={display.hex}
onChange={(value) => {
setDisplay((current) => ({ ...current, hex: value }));
commit(value);
}}
onBlur={() => setDisplay((current) => ({ ...current, hex: color }))}
/>
</InlineGrid>
<InlineGrid gap="400" columns="40px auto" alignItems="center">
<Text as="span">RGB</Text>
<InlineGrid gap="050" columns={3}>
{['red', 'green', 'blue'].map((channel) => (
<TextField key={channel} label={channel} labelHidden type="number" autoComplete="off" min={0} max={255} value={String(display[channel])} onChange={(value) => handleRgbChange(channel, value)} />
))}
</InlineGrid>
</InlineGrid>
</BlockStack>
</Box>
<Divider />
<Box paddingInline="300">
<InlineStack gap="200" wrap>
{COLOR_PRESETS.map((preset) => (
<UnstyledButton key={preset} accessibilityLabel={`Use ${preset}`} style={{ ...SWATCH_STYLE, background: preset }} onClick={() => commit(preset)} />
))}
</InlineStack>
</Box>
</BlockStack>
</Box>
</Popover>
</BlockStack>
</Card>
);
};
export const Example = () => (
<Box minHeight="500px">
<InlineGrid columns={{ xs: 1, sm: 3 }} gap="400">
{COLOR_FIELDS.map((field) => <ColorPickerCard key={field.label} {...field} />)}
</InlineGrid>
</Box>
);