Higher Order Components for touch and mouse events control.
This component is useful for better touchscreen and mouse events recognition. Especially, if you need to handle different actions for hybrid devices.
For example, you have a navigation bar with dropdowns. You need to navigate to some url when clicking on a link, open dropdown menu on hover, as well as open dropdown when tapping the link by finger. Commonly, tapping on hybrid devices opens dropdown for a moment and then navigates to the url defined in the link. Because click
event follows the mouseenter
and touchstart
events. Check all mouse and touch events sequence in my codepen test ground.
npm install --save react-touch-mouse-handler
To make everything working you need to:
- Create a method which receives event type argument (myAction in example).
- Wrap your component in a function inside
TouchMouseHandler
component. This child function accepts events argument which should be passed your component. - Pass these events farther to the DOM element.
- Write different actions for different event types.
import React, { Component } from 'react'
import TouchMouseHandler from 'react-touch-mouse-handler';
export default class App extends Component {
myAction = (eventType) => {
if (eventType === 'touch') {
// do something if it was touch event (tap)
}
if (eventType === 'mouse') {
// do something if it was mouse event (mouseenter)
}
}
render() {
return (
<TouchMouseHandler handleAction={this.myAction}>
{(events) => (
<Button events={events}>Click me</Button>
)}
</TouchMouseHandler>
);
}
}
const Button = ({events}) => (
<button {...events}>Click me</button>
);
If you have ideas for improvements, please open an issue.
MIT © seleckis