Skip to content

Instantly share code, notes, and snippets.

@ComicDansMS
Created December 31, 2023 00:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ComicDansMS/02612050b5d979df9e9aea436ff16a81 to your computer and use it in GitHub Desktop.
Save ComicDansMS/02612050b5d979df9e9aea436ff16a81 to your computer and use it in GitHub Desktop.
Shopify Polaris colour picker with using HEX, including text input and swatch
import {
ColorPicker,
hsbToHex,
hexToRgb,
rgbToHsb,
InlineStack,
BlockStack,
TextField
} from "@shopify/polaris";
import { useCallback, useEffect, useState } from "react";
export default function ColourPickerWithHex({ hex, setHex }) {
const [hsb, setHsb] = useState(hexToHsb(hex));
const [hexField, setHexField] = useState(hex);
const [inputError, setInputError] = useState(false);
useEffect(() => {
setHsb(hexToHsb(hex));
setHexField(hex);
}, [hex]);
const handleColorPickerChange = useCallback((hsbValue) => {
const newHex = hsbToHex(hsbValue);
setHsb(hsbValue);
setHex(newHex);
setHexField(newHex);
}, [setHex]);
const handleTextChange = useCallback((hexValue) => {
setHexField(hexValue);
const isValidHex = /^#?([0-9A-F]{6})$/i.test(hexValue);
if (isValidHex) {
try {
const newHsb = hexToHsb(hexValue);
setHsb(newHsb);
setHex(hexValue);
setInputError(false);
} catch (error) {
setInputError(true);
}
} else {
setInputError(true);
}
}, [setHex]);
const Swatch = ({ value }) => {
return (
<div style={{
width: '2rem',
height: '2rem',
borderRadius: '0.25rem',
background: value,
}} />
)
}
return (
<BlockStack gap="200">
<ColorPicker onChange={handleColorPickerChange} color={hsb} />
<div style={{width:"12rem"}}>
<InlineStack gap="200" wrap={false}>
<Swatch value={hex}/>
<TextField
label=""
value={hexField}
onChange={(value) => handleTextChange(value)}
autoComplete="off"
error={inputError}
/>
</InlineStack>
</div>
</BlockStack>
);
}
function hexToHsb(hex) {
const rgb = hexToRgb(hex);
const hsb = rgbToHsb(rgb);
return hsb;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment