Cannot use react-color Saturation with @types/react-color

1.2k Views Asked by At

I am trying to create a custom color picker using react-color library (^2.19.3) with @types/react-color (^3.0.4). As Saturation component is not exported from types index file the only way to how to import it is react-color/lib/components/common. Using Saturation like (this):

<Saturation color={props.color} onChange={onChange} />

Will trigger an error Uncaught TypeError: Cannot read property 'h' of undefined (Types are not the same as original Saturation from react-color library).

I created minimal example (just uncomment Saturation section). Any Ideas on how to use Saturation component?

2

There are 2 best solutions below

0
tprieboj On BEST ANSWER

I found out what latest versions of both libraries are not compatible. After installation of @types/[email protected] problem disappeared with the usage of:

<Saturation hsl={props.hsl} hsv={props.hsv} ... />
5
Mic Fung On

Passing {...props} will solve your problem where props has color, hsl, hex, hsv etc.

color: "orange"
hsl: Object
    h: 38.82352941176471
    s: 1
    l: 0.5
    a: 1
hex: "#ffa500"
    rgb: Object
    r: 255
    g: 165
    b: 0
    a: 1
hsv: Object
    h: 38.82352941176471
    s: 1
    v: 1
    a: 1
oldHue: 38.82352941176471
source: undefined
onChange: ƒ () {}

I read the source, they need hsl.h, hsl.v, hsl.s to do the colouring. The hsl and hsv will be calculated by react-color based on the color and you just need to pass it to its component to use.


<Saturation
  {...props}
  onChange={(color: Color | ColorResult) => props.onChange?.(color)}
/>

Here is the codesandbox

https://codesandbox.io/s/silent-pond-vnsh6?file=/src/custom-theme-color-picker.tsx:865-875