Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

onMouseUp not working if you drag outside of the component #199

Open
jameschetwood opened this issue Mar 31, 2023 · 1 comment
Open

onMouseUp not working if you drag outside of the component #199

jameschetwood opened this issue Mar 31, 2023 · 1 comment

Comments

@jameschetwood
Copy link

I need to have 2 pieces of state. One updates in real time as you drag on the colour picker, and the other only updates when you release the drag (ie you've finished choosing).

This code works except when you drag the mouse out of the component. In that case color updates but colorFinal does not.

https://codesandbox.io/s/funny-wind-y65ivg?file=/src/App.js:0-555

import { useState } from "react";
import "./styles.css";
import { HexColorPicker } from "react-colorful";

export default function App() {
  const [color, setColor] = useState("#aabbcc");
  const [colorFinal, setColorFinal] = useState("#aabbcc");
  return (
    <div>
      <div style={{ background: color }}>Color</div>
      <div style={{ background: colorFinal }}>Color Final</div>
      <HexColorPicker
        color={color}
        onChange={setColor}
        onMouseUp={(e) => {
          setColorFinal(color);
        }}
      />
    </div>
  );
}

Screen recording of the issue: https://www.loom.com/share/0d4ad40582d64ccf94d0454e74d6fbe9

Is there an event that could be used instead of or as well as onMouseUp ?

@Space1nvader
Copy link

Space1nvader commented Jul 20, 2023

Hi, if you need still fix it, i have a stupid solution

Add new state
const [isSettingColor, setIsSettingColor] = useState(false);

Add mouseDown listener on color-picker component
onMouseDown={() => setIsSettingColor(true)}

And effect

  useEffect(() => {
    const changeColorHandler = () => {
        onChange(color);
    };

    if (color && isSettingColor) {
      window.addEventListener('mouseup', changeColorHandler);
    } else {
      window.removeEventListener('mouseup', changeColorHandler);
    }

    return () => {
      window.removeEventListener('mouseup', changeColorHandler);
    };
  }, [customColor, isSettingColor]);

If you have a better solution, I'd be grateful to see it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants