javascript
50 lines · 7 steps
A validated color picker in React
Two uncontrolled inputs share one committed color, validated and synced through a single commit function.
Explained by
highlit
1import { useCallback, useRef, useState } from 'react';
2
3export function ColorPicker({ initialColor = '#3b82f6', onCommit }) {
4 const [committed, setCommitted] = useState(initialColor);
5 const swatchRef = useRef(null);
6 const hexRef = useRef(null);
7
8 const normalize = (value) => {
9 const trimmed = value.trim().replace(/^#?/, '#').toLowerCase();
10 return /^#[0-9a-f]{6}$/.test(trimmed) ? trimmed : null;
11 };
12
13 const commit = useCallback(
14 (raw) => {
15 const next = normalize(raw);
16 if (!next || next === committed) {
17 if (hexRef.current) hexRef.current.value = committed;
18 return;
19 }
20 setCommitted(next);
21 if (swatchRef.current) swatchRef.current.value = next;
22 if (hexRef.current) hexRef.current.value = next;
23 onCommit?.(next);
24 },
25 [committed, onCommit],
26 );
27
28 return (
29 <div className="color-picker">
30 <input
31 ref={swatchRef}
32 type="color"
33 aria-label="Pick color"
34 defaultValue={committed}
35 onBlur={(e) => commit(e.target.value)}
36 />
37 <input
38 ref={hexRef}
39 type="text"
40 inputMode="text"
41 spellCheck={false}
42 maxLength={7}
43 defaultValue={committed}
44 onBlur={(e) => commit(e.target.value)}
45 onKeyDown={(e) => e.key === 'Enter' && e.currentTarget.blur()}
46 />
47 <span className="color-picker__preview" style={{ backgroundColor: committed }} />
48 </div>
49 );
50}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Uncontrolled inputs with refs let you validate on commit rather than re-rendering on every keystroke.
- 2A single normalize-and-commit path keeps multiple inputs and derived UI in sync from one source of truth.
- 3Rejecting invalid or unchanged input by resetting the field's value gives users immediate, honest feedback.
Related explainers
javascript
const express = require('express'); const { createProxyMiddleware, fixRequestBody } = require('http-proxy-middleware'); const router = express.Router();
Building an API gateway proxy in Express
reverse-proxy
middleware
api-gateway
Intermediate
6 steps
go
package middleware import ( "net/http"
A content-type guard middleware in Gin
middleware
closures
http
Intermediate
7 steps
javascript
import { useEffect, useRef } from 'react'; export function useRefetchOnFocus(refetch, { staleTime = 30_000 } = {}) { const lastFetchedAt = useRef(Date.now());
A React hook that refetches on tab focus
custom-hooks
refs
event-listeners
Intermediate
6 steps
go
package api import ( "errors"
Turning Gin validation errors into JSON
validation
error-handling
http-handlers
Intermediate
9 steps
javascript
import { NextResponse } from 'next/server'; import { Redis } from '@upstash/redis'; const redis = Redis.fromEnv();
Sliding-window rate limiting in a Next.js route
rate-limiting
redis
sorted-set
Advanced
8 steps
javascript
const MAX_FILE_SIZE = 5 * 1024 * 1024; const ALLOWED_TYPES = { 'image/jpeg': ['jpg', 'jpeg'],
Validating file uploads by content, not just claims
input-validation
security
magic-bytes
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-validated-color-picker-in-react-explained-javascript-a35d/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.