Preview
Installation
CLI
npx shadcn@latest add https://kelvinmai.io/r/color-picker.json
Manual
Install the following dependencies
npm install clsx tailwind-merge react-colorful
Add a classname utility function
import { clsx, type ClassValue } from 'clsx';import { twMerge } from 'tailwind-merge';export const cn = (...inputs: ClassValue[]) => {return twMerge(clsx(inputs));};
Copy and paste the following code into your project
components/color-picker.tsx
'use client';import * as React from 'react';import { HexAlphaColorPicker, HexColorPicker } from 'react-colorful';import { Input } from '@/components/ui/input';import { cn } from '@/lib/utils';export type ColorPickerProps = Omit<React.ComponentProps<typeof Input>,'value' | 'onChange' | 'onBlur'> & {value?: string;alpha?: boolean;onChange: (value: string) => void;};export const ColorPicker: React.FC<ColorPickerProps> = ({className,value,alpha,onChange,...props}) => {return (<div className={cn('space-y-2', className)}>{alpha ? (<HexAlphaColorPicker color={value} onChange={onChange} {...props} />) : (<HexColorPicker color={value} onChange={onChange} {...props} />)}<Inputid='custom'value={value}className='h-8 w-[200px]'onChange={(e) => onChange(e.currentTarget.value)}{...props}/></div>);};ColorPicker.displayName = 'ColorPicker';
Update the import paths to match your project setup
Usage
import { ColorPicker } from '@/components/ui/color-picker';export default function ColorPickerDemo() {const [color, setColor] = React.useState('#fff');return <ColorPicker value={color} onChange={setColor} />;}
API Reference
Props
Name | Type | Required | Default | Description |
---|---|---|---|---|
alpha | boolean | No | undefined | A boolean to check whether or not to include color alpha picker. |