I'm trying to implement a custom color picker using React-Color and I've hit a snag.
You can see a simplified example of my issue here:
https://codesandbox.io/s/react-color-multiple-custom-pickers-q0eiq
The initial state comes through correctly but as soon as I try to interact with the components the entire thing explodes. It looks like the new state I'm setting is missing a bunch of the original properties and I have no idea why.
I'm extremely new to React...
[Edit]
Updated main link with final working version. Special thanks to @ravibagul91 for helping me work through the problem.
You should be sending key
to onChange
handler to update the appropriate key in the state,
<div style={{ position: "relative", zIndex: 0 }}>
<div style={{
height: "100px",
width: "100px",
position: "relative",
float: "left",
zIndex: 1000000
}}>
<Saturation hsl={swatch.hsl} hsv={swatch.hsv} onChange={(e)=> handleChange(e, 'hsv')} /> //Provide key to update
</div>
<div style={{
marginLeft: "10px",
height: "100px",
width: "10px",
position: "relative",
float: "left",
zIndex: 1000000
}}>
<Hue hsl={swatch.hsl} direction="vertical" onChange={(e)=> handleChange(e,'hsl')} /> //Provide key to update
</div>
<EditableInput value={swatch.hex} onChange={(e)=> handleChange(e, 'hex')} /> //Provide key to update
</div>
Your change handler should be this,
const handleChange = (c, key) => {
setSwatch(l => ({...l , [key]: c}))
};
Finally you can watch the change,
useEffect (() => {
console.log(swatch)
},[swatch])