Skip to content

Instantly share code, notes, and snippets.

@guillermo
Created May 9, 2019 14:19
Show Gist options
  • Save guillermo/7b37fbcc56165099cdb5d1692450057b to your computer and use it in GitHub Desktop.
Save guillermo/7b37fbcc56165099cdb5d1692450057b to your computer and use it in GitHub Desktop.
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