https://github.com/bence-toth/react-hook-mouse
A React hook to access mouse position, movement and button states
https://github.com/bence-toth/react-hook-mouse
mouse mouse-button mouse-events mouse-tracking react react-hooks
Last synced: 12 months ago
JSON representation
A React hook to access mouse position, movement and button states
- Host: GitHub
- URL: https://github.com/bence-toth/react-hook-mouse
- Owner: bence-toth
- License: lgpl-3.0
- Created: 2019-02-16T22:41:12.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2023-03-04T03:09:31.000Z (over 3 years ago)
- Last Synced: 2025-06-06T09:08:16.842Z (about 1 year ago)
- Topics: mouse, mouse-button, mouse-events, mouse-tracking, react, react-hooks
- Language: JavaScript
- Size: 195 KB
- Stars: 0
- Watchers: 1
- Forks: 1
- Open Issues: 7
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# react-hook-mouse :mouse:
A React hook to access data from mouse events.
## Installation
Using `npm`:
```sh
npm install --save react-hook-mouse
```
Using `yarn`:
```sh
yarn add react-hook-mouse
```
## Usage
```jsx
import React from 'react'
import useMouse from 'react-hook-mouse'
const displayCoordinates = ({x, y}) => `${x} : ${y}`
const displayFlag = flag => flag ? 'Yes' : 'No'
const ComponentWithMouse = () => {
const mouse = useMouse()
return (
-
Mouse position in viewport:
{displayCoordinates(mouse.position.client)}
-
Mouse position on page:
{displayCoordinates(mouse.position.page)}
-
Mouse position on screen:
{displayCoordinates(mouse.position.screen)}
-
Mouse movement:
{displayCoordinates(mouse.movement)}
-
Left button was pressed:
{displayFlag(mouse.buttons.left)}
-
Right button was pressed:
{displayFlag(mouse.buttons.right)}
-
Middle button was pressed:
{displayFlag(mouse.buttons.middle)}
-
Alt key was pressed:
{displayFlag(mouse.keyboard.alt)}
-
Ctrl key was pressed:
{displayFlag(mouse.keyboard.ctrl)}
-
Meta key was pressed:
{displayFlag(mouse.keyboard.meta)}
-
Shift key was pressed:
{displayFlag(mouse.keyboard.shift)}
)
}
```
## Caveats
Data in `mouse.keyboard` is always read from a `MouseEvent` and therefore it will only get updated on mouse events, not when the keys are actually pressed on the keyboard.
## Contributions
Contributions are welcome. File bug reports, create pull requests, feel free to reach out at tothab@gmail.com.
## Licence
LGPL-3.0