omgovich / react-colorful

🎨 A tiny (2,8 KB) color picker component for React and Preact apps
https://omgovich.github.io/react-colorful
MIT License
3.19k stars 100 forks source link

Usage with classes? #185

Closed matronator closed 2 years ago

matronator commented 2 years ago

Hi, is it possible to use this with classes? When I put this into a class with onChange={this.changeColor} the whole page turns completely white as soon as I click on any color and some errors pop-up in the console.

omgovich commented 2 years ago

Hi! I'm pretty sure that the component works inside class components. Please share your changeColor code.

matronator commented 2 years ago

Nevermind, I got it working. I don't know why, but adding the onChange as a reference to a class function (like in the original comment onChange={this.onChange}) just kept crashing. I finally got it to work when I inlined the entire function, so it looks like this:

<PopoverPicker
  color={this.state.preview.color}
  selectValue={this.state.preview.style}
  onChange={(color: string) => this.setState({ preview: { ...this.state.preview, color: color }})}
/>

Can't figure out why it only seems to work when it's inlined like this, though.

omgovich commented 2 years ago

My guess: it loses this context. Try:

- onChange={this.changeColor}
+ onChange={this.changeColor.bind(this)}

or make changeColor an arrow method:

- changeColor(color: string) {
+ changeColor = (color: string) => {