d22dc80 Apr 1, 2018
1 contributor

Users who have contributed to this file

146 lines (104 sloc) 2.73 KB


Render prop that re-renders on mouse position change.


import {MouseSensor} from 'libreact/lib/MouseSensor';

<MouseSensor>{(state) =>
  <pre>{JSON.stringify(state, null, 4)}</pre>


MouseSensor passes its state to render props, with the following signature:

interface IMouseSensorState {
  docX: number;
  docY: number;
  posX: number;
  posY: number;
  elH: number;
  elW: number;
  elX: number;
  elY: number;

, where

  • docX and docY — mouse position in document.
  • posX and posY — mouse position in your element.
  • elW and elH — element dimensions.
  • elX and elY — element position.


interface IMouseSensorProps {
  bond?: string | boolean;
  whenHovered?: boolean;

, where

  • bond — optional, boolean or string, specifying bondig spread object. If string, it specifies the name of the bonding object injected into state, if boolean and true the bonding object will have its default name bond.
  • whenHovered — optional, boolean, when true, will track mouse position only when target element is hovered, defaults to false.
  • onMouseMove — optional, callback called on every mouse move, receives state as a single argument.


Below is an example that uses optional bond prop, which allows to attach listeners to any React HTML element.

import {MouseSensor} from 'libreact/lib/MouseSensor';

<MouseSensor bond>{(state) =>
    <div {} style={{
      width: 300,
      height: 300,
      border: '1px solid tomato',
      margin: '100px'
    }} />
    <pre style={{fontFamily: 'monospace'}}>
      {JSON.stringify(state, null, 4)}

Result example

    "docX": 128,
    "docY": 277,
    "posX": 108,
    "posY": 100,
    "elH": 302,
    "elW": 302,
    "elX": 20,
    "elY": 177,

withMouse() HOC

HOC that merges mouse prop into enhanced component's props.

import {withMouse} from 'libreact/lib/MouseSensor';

const MyCompWithMouseAndBond = withMouse(MyComp);

You can overwrite the injected prop name

const MyCompWithMouseAndBond = withMouse(MyComp, 'foo');

Or simply merge the whole object into your props

const MyCompWithMouseAndBond = withMouse(MyComp, '');

@withMouse decorator

React stateful component decorator that adds mouse prop.

import {withMouse} from 'libreact/lib/MouseSensor';

class MyComp extends Component {


Specify different prop name

class MyComp extends Component {


or merge the the whole state object into props

class MyComp extends Component {