Skip to content
Advertisement

How do I get the color of a color-picker on button click?

Background:

I am trying to get the current value of a color picker when I click my onSubmit button. The color picker is in a separate component.

Problem:

When I change the color via the color picker, I am getting an error message that says: TypeError: _this.props.setSelectedColor is not a function

Component that has Color Picker Inside of It:

function myFunctionA(props) {

  const [selectedColor, setSelectedColor] = useState(null)

  const handleSubmit = useCallback(() => {
    console.log(selectedColor);
  });

  return (
    <>
      <Form onSubmit={handleSubmit}>
        <MyColorPicker setSelectedColor/>
      </Form>
    </>
  )
}

Color Picker Code:

class MyBlockPicker extends React.Component {
  state = {
    background: this.props.background,
  };

  handleChangeComplete = (color) => {
    console.log(color);
    this.setState({ background: color.hex });
    this.props.setSelectedColor(color.hex)
  };

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

export default MyBlockPicker;

Any ideas on how to fix?

Advertisement

Answer

If you want to pass a function down to a child you need to do it like this:

<MyColorPicker setSelectedColor={setSelectedColor} />
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement