useEyeDropper
Pick colors from the entire screen using the modern EyeDropper API.
EyeDropper API not supported
This feature requires a Chromium-based browser (Chrome, Edge, Opera).
Usage
import { useEyeDropper } from 'usehooks-ts'
export default function App() {
const { isSupported, open } = useEyeDropper()
const pickColor = async () => {
const result = await open()
if (result) {
console.log('Selected color:', result.sRGBHex)
}
}
if (!isSupported) return <p>Browser not supported</p>
return <button onClick={pickColor}>Pick Color</button>
}API
const { isSupported, open } = useEyeDropper()Return Values
| Name | Type | Description |
|---|---|---|
isSupported | boolean | true if the browser supports EyeDropper API |
open | (options?) => Promise | Function to open the eye dropper tool |
Hook
import { useCallback, useMemo, useState } from 'react'
export interface EyeDropperOpenOptions {
signal?: AbortSignal
}
export interface EyeDropperResult {
sRGBHex: string
}
export interface UseEyeDropperReturn {
isSupported: boolean
open: (options?: EyeDropperOpenOptions) => Promise<EyeDropperResult | undefined>
}
export function useEyeDropper(): UseEyeDropperReturn {
const isSupported = useMemo(() => {
if (typeof window === 'undefined') return false
return 'EyeDropper' in window
}, [])
const open = useCallback(
async (options?: EyeDropperOpenOptions): Promise<EyeDropperResult | undefined> => {
if (!isSupported) {
return undefined
}
// @ts-ignore
const eyeDropper = new window.EyeDropper()
try {
const result = await eyeDropper.open(options)
return result
} catch (e) {
return undefined
}
},
[isSupported],
)
return { isSupported, open }
}