Skip to content

Instantly share code, notes, and snippets.

@pkayokay
Created November 5, 2024 21:40
Show Gist options
  • Save pkayokay/1b80c0151f4729fbfd4219c559a69a6c to your computer and use it in GitHub Desktop.
Save pkayokay/1b80c0151f4729fbfd4219c559a69a6c to your computer and use it in GitHub Desktop.
React ColorInput Component
input[type="color"] {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
width: 1.2rem;
height: 1rem;
position: absolute;
left: 0.9rem;
top: 1.2rem;
background-color: transparent;
border: none;
cursor: pointer;
}
input[type="color"]::-webkit-color-swatch {
border-radius: 0.2em;
border: 1px solid #e9e9e9;
}
input[type="color"]::-moz-color-swatch {
border-radius: 0.2em;
border: 1px solid #e9e9e9;
}
export const ColorInput = ({
id,
label,
value,
onChange,
}: {
id: string;
label: string;
description?: string;
placeholder?: string;
value?: string;
onChange: (value: string) => void;
}) => {
const colorRef = useRef<HTMLInputElement>(null);
const textRef = useRef<HTMLInputElement>(null);
const handleInputClick = () => {
colorRef?.current?.focus();
colorRef?.current?.click();
};
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
onChange(e.target.value);
};
return (
<div className="relative mb-5>
<label htmlFor={id}>
<span>{label}</span>
</label>
<div className="flex relative items-center">
<span
onClick={handleInputClick}
className="z-20 cursor-pointer size-5 shadow absolute left-3.5 top-[0.9rem] rounded-sm"
style={{ backgroundColor: value || "#000000" }}
></span>
<input tabIndex={-1} ref={colorRef} id={id} type="color" value={value} className="z-10 pointer-events-none" onChange={handleChange} />
<input
ref={textRef}
id={id}
type="text"
className="!pl-[2.8rem] disabled:text-neutral-400 w-full bg-white !mt-0.5 border !px-3.5 h-[2.8rem] !rounded-[0.3rem] focus:!ring-[3px] focus:!ring-sky-200/50 focus:!border-sky-600 !border-neutral-400/60 !placeholder-neutral-400"
value={value}
onClick={handleInputClick}
onChange={handleChange}
/>
</div>
</div>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment