Home > database >  Get mouse X position from clicked in react
Get mouse X position from clicked in react

Time:08-07

In React I'm trying to get mouse X position after click, if I click in middle of page and move it right it must start counting from 0 not from actual e.clientX would count

here is What I do but seems like doesn't work

import React, {useState, useEffect} from 'react';

const App = () => {
  const [startPosition, setStartPosition] = useState(0)

  const mouseMove = (e) => {
    console.log(e.clientX - startPosition)
  }

  const mouseClick = (e) => {
    setStartPosition(e.clientX)
  }

  useEffect(() => {
    window.addEventListener("mousedown", mouseClick)
    window.addEventListener("mousemove", mouseMove)

    return () => {
      window.removeEventListener("mousedown", mouseClick)
      window.removeEventListener("mousemove", mouseMove)
    }
  },[])

  return (
    <div className='App' />
  );
}

export default App

this code still prints e.clientX not actual cordinates from clicked

CodePudding user response:

If you want to get position when click, you need using onClick Event Listeners.

Example:

const App = () => {
  const [startPosition, setStartPosition] = useState(0);

  const mouseClick = (e) => {
    setStartPosition(e.clientX);
    console.log(e.clientX);
  };

  return <div className="App" onClick={mouseClick} />;
};

Maybe you need add height style for .App like: .App: { height: 100vh }

CodePudding user response:

in useEffect while using window events [] as second argument isn't necessary

  useEffect(() => {
    window.addEventListener("mousedown", mouseClick)
    window.addEventListener("mousemove", mouseMove)

    return () => {
      window.removeEventListener("mousedown", mouseClick)
      window.removeEventListener("mousemove", mouseMove)
    }
  })

after doing this it works now

  • Related