skip to Main Content

I need to get click coordinate using an event listener and store it using react hook usestate so i can use it to display a menu.

it seems like usestate is asynchronous and the value update only in the second click.

My code below :

const [xPosition, setXPosition] = useState<number>(0);
const [yPosition, setYPosition] = useState<number>(0);
let cmenu;


const btnClick = () => {
document.addEventListener("click", function (event) {
  let x = event.pageX;
  let y = event.pageY;
  setYPosition(y);
  setXPosition(x);
});
cmenu.open(yPosition, xPosition);
  };

Thanks

3

Answers


  1. At first glance, it seems to me that you don’t understand the functionality of React.

    Your code is only added by the listener to the element after the first click.

    Login or Signup to reply.
  2. I’m not sure what you try to achieve here, but the onClick function from a button provide an event parameter:

    const btnClick = (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
        cmenu.open(event.clientX, event.clientY);
      };
    

    you should call this function like this for instance:

      <button onClick={btnClick}>click</button>
    
    Login or Signup to reply.
  3. You need to use these coordinates immediately within your event listener. Heres a more straightforward version of your code:

      const [xPosition, setXPosition] = useState(0);
      const [yPosition, setYPosition] = useState(0);
      let cmenu;
    
      useEffect(() => {
        const handleClick = (event) => {
          setXPosition(event.pageX);
          setYPosition(event.pageY);
          cmenu.open(event.pageY, event.pageX); // Use the coordinates directly
        };
    
        document.addEventListener('click', handleClick);
        return () => document.removeEventListener('click', handleClick);
      }, []);
    

    There may be some issue with the parenthesis but hope so it can give you general idea about your problem

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search