Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
React Hooks relative mouse position used in kalena.app https://blog.kalena.app/day-6/
// Inspired by
// https://github.com/rehooks/window-mouse-position/blob/master/index.js
import {useState,useEffect} from 'react'
export default function useMousePosition(){
let [mousePosition, setMousePosition] = useState([0,0])
function handleMouseMove(e) {
setMousePosition( [e.pageX, e.pageY] );
}
useEffect(()=>{
window.addEventListener("mousemove", handleMouseMove)
return () => {
window.removeEventListener("mousemove", handleMouseMove)
}
});
return mousePosition;
}
import React from 'react'
import useMousePosition from 'useMousePosition'
export function MousePosition(){
let [mouseX,mouseY] = useMousePosition()
return <div>x: {mouseX} y:{mouseY}</div>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.