Created
May 9, 2019 14:19
-
-
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/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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