0
votes

I want to use this color picker in my React project https://casesandberg.github.io/react-color/#about

Here is example from docs

import React from 'react';
import { SketchPicker } from 'react-color';

class Component extends React.Component {
  state = {
    background: '#fff',
  };

  handleChangeComplete = (color) => {
    this.setState({ background: color.hex });
  };

  render() {
    return (
      <SketchPicker
        color={ this.state.background }
        onChangeComplete={ this.handleChangeComplete }
      />
    );
  }
}

But it's class component. I have functional with useState in my project. One of them is

const [projectColor, setProjectColor] = useState("#F9A8D4");

with default picked color. How to rewrite this class example to use with usestate? I don't get it...

onChangeComplete={ this.handleChangeComplete }

is like setState? And from where is this color variable?

handleChangeComplete = (color) => {
    this.setState({ background: color.hex });
  };

Here is my full code (i don't know what pass to the setProjectColor). Colors is array with colors to pick, and color is default selected color.

const [projectColor, setProjectColor] = useState("#F9A8D4");
  const colors = [
    "#FECACA",
    "#F9A8D4",
    "#FDE68A",
    "#A7F3D0",
    "#BFDBFE",
    "#E5E7EB",
  ];

  const colorPicker = () => {
    return (
      <div className="p-4">
        <CirclePicker
          colors={colors}
          color={projectColor}
          onChangeComplete={(e) => setProjectColor(projectColor)}
        />
      </div>
    );
  };
2

2 Answers

1
votes

You only need to use the color object of onChangeComplete callback:

onChangeComplete={(color) => setProjectColor(color.hex)

Full example:

const [projectColor, setProjectColor] = useState("#F9A8D4");

return (
  <div className="p-4">
    <CirclePicker
      colors={colors}
      color={projectColor}
      onChangeComplete={(color) => setProjectColor(color.hex)}
    />
  </div>
);
0
votes

You can rewrite your function:

 handleChangeComplete = (color) => {
    this.setState({ background: color.hex });
  };

into:

const handleChangeComplete = React.useCallback((color) => setProjectColor(color), []);