An open API service indexing awesome lists of open source software.

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

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