Why is my React Color popup not updating?

1.9k Views Asked by At

I am attempting to create a button which pops up a react-color SketchPicker component(akin to the first example listed in react-color's "More Examples"). However, when I open my popup and drag the selector in SketchPicker, the color in the UI does not update, and the selector does not move.

I have perused my component, and I cannot find a single aspect of it in error; I have merely updated the first component in More Examples to utilize useState.

Why is this?

CodeSandbox

1

There are 1 best solutions below

0
Kishore S On

You need to pass a color prop to SketchPicker component and also add an onChange handler so whenever you move the cursor this handler triggers and it has access to selected color which you can update the state variable and pass that state variable to color prop.

import React, { useState } from "react";
import "./ColorSelector.css";
import { SketchPicker } from "react-color";

const ColorSelector = () => {
  const [display, setDisplay] = useState(false);
  const [color, setColor] = useState({
    r: "241",
    g: "112",
    b: "19",
    a: "1"
  });
  const onClickMethod = () => {
    setDisplay(!display);
  };

  const onCloseMethod = () => {
    setDisplay(false);
  };

  const onChangeMethod = (color) => {
    setColor({ ...color.rgb });
  };

  const popover = {
    position: "absolute",
    zIndex: "3"
  };

  const cover = {
    position: "fixed",
    top: "0px",
    right: "0px",
    bottom: "0px",
    left: "0px"
  };

  return (
    <div>
      <a className="colorSelector" onClick={onClickMethod}>
        select color
      </a>
      {display ? (
        <div style={popover}>
          <div style={cover} onClick={onCloseMethod} />
          <SketchPicker color={color} onChange={onChangeMethod} />
        </div>
      ) : null}
    </div>
  );
};

export default ColorSelector;