normalizeHex
normalizeHex(text) turns a three- or six-digit hex color, with or without #, into #rrggbb in lower case, and returns null for anything else. f80 becomes #ff8800, #3366CC becomes #3366cc, and red or #ff88 give null. Spaces around the text are ignored. Use it to check a hex color someone types before a ColorPicker or a swatch takes it.
On this page
import { Code, Field, Label, normalizeHex, Stack } from '@tounsoo/todae';
import { useId, useState } from 'react';
export default function NormalizeHexInput() {
const id = useId();
const [text, setText] = useState('f80');
const hex = normalizeHex(text);
return (
<Stack.Root gap="condensed">
<Field.Group>
<Label.Root htmlFor={id}>Brand color</Label.Root>
<Field.Root id={id} name="brand" invalid={hex === null}>
<Field.TextInput value={text} onChange={(event) => setText(event.target.value)} />
</Field.Root>
</Field.Group>
<Code.Root>{hex ?? 'null'}</Code.Root>
</Stack.Root>
);
}
#ff8800With a color picker
ColorPicker.Root reads and writes #rrggbb. Beside a Field.Picker with swatch, a Field.TextInput holds the text someone types, and normalizeHex decides when it is a color the picker can take. Keep the text as typed while it is null, so a half-typed color isn't thrown away.
Accessible composition
Todae handles: Nothing on screen: it returns a string or null.
You supply: A message that says what's wrong when the text is not a color, in an ErrorMessage tied to the field, and invalid on the Field.Root. A color shown as text too, not only as a swatch.
Watch for: Marking a field invalid on every keystroke while someone is still typing; a commit, such as blur, is a kinder time to say so.
When to use
When: Checking or tidying a hex color someone types, such as in a theme editor or beside a color picker.
When not: A color in another syntax, such as oklch() → parseThemeColor.
Props
| Name | Type | Description |
|---|---|---|
text Required | string | The text to read, such as typed input. Spaces around it are ignored. |