Giter VIP home page Giter VIP logo

react-hammerjs's Introduction

React-HammerJS

ReactJS / HammerJS integration. Support touch events in your React app.

If you're looking for native tap event handling in ReactJS, check out my react-tappable package.

Installation

The easiest way to use React-HammerJS is to install it from NPM and include it in your own React build process (using Browserify, etc).

You can also use the standalone build by including dist/hammer.js in your page. If you use this, make sure you have already included React, and it is available as a global variable.

npm install react-hammerjs --save

Usage

React-HammerJS wraps a React component, binding Hammer events to it so it can fire the handlers specified.

Properties

Event Listener properties

  • onTap
  • onDoubleTap
  • onPan
  • onPanCancel
  • onPanEnd
  • onPanStart
  • onPinch
  • onPinchCancel
  • onPinchEnd
  • onPinchIn
  • onPinchOut
  • onPinchStart
  • onPress
  • onPressUp
  • onRotate
  • onRotateCancel
  • onRotateEnd
  • onRotateMove
  • onRotateStart
  • onSwipe
  • action - like the onTap event handler but will also be fired onPress.

Behavior properties

  • direction - (string) 'DIRECTION_ALL' | 'DIRECTION_HORIZONTAL' | 'DIRECTION_VERTICAL'. Used to restrict the pan and swipe direction. These string values may also work: 'DIRECTION_NONE' |'DIRECTION_LEFT' | 'DIRECTION_RIGHT' | 'DIRECTION_UP' | 'DIRECTION_DOWN'.

  • options - can be used to configure the Hammer manager. These properties will be merged with the default ones.

Example

var Hammer = require('react-hammerjs');

// Default options
<Hammer onTap={handleTap} onSwipe={handleSwipe}><div>Tap Me</div></Hammer>

// Custom options
var options = {
    touchAction:'compute',
    recognizers: {
        tap: {
            time: 600,
            threshold: 100
        }
    }
};

<Hammer onTap={handleTap} options={options}><div>Tap Me</div></Hammer>

Disabled Events

As a default, the pinch and rotate events are disabled in hammer.js, as they would make actions on an element "blocking". You may enable these events using the options object which is a attribute on the react <Hammer> element.

For example, to activate the pinch event on a canvas element:

<Hammer
    onPinch={handlePinch}
    options={{
       recognizers: {
          pinch: { enable: true }
       }
    }}>
    <canvas></canvas>
</Hammer>

Disabled events are detailed in the hammer.js api documentation:

License

MIT Licensed. Copyright (c) Jed Watson 2017.

react-hammerjs's People

Contributors

akofman avatar benjeffery avatar chrisdoc avatar cmilfont avatar disusered avatar djansen88 avatar edelisa avatar fuechter avatar georgs avatar gwu avatar hepiyellow avatar jedwatson avatar juice49 avatar mdjasper avatar nathantalewis avatar seamusleahy avatar silentcloud avatar smucode avatar tomconroy avatar wmertens avatar yiminghe avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-hammerjs's Issues

global "direction" variable

In src/Hammer.js:

function updateHammer (hammer, props) {
        if (props.hasOwnProperty('vertical')) {
                console.warn('vertical is deprecated, please use `direction` instead');
        }

        var directionProp = props.direction;
        if (directionProp || props.hasOwnProperty('vertical')) {
                direction = directionProp ? directionProp : (props.vertical ? 'DIRECTION_ALL' : 'DIRECTION_HORIZONTAL');

so it's creating a global window.direction variable, which is a bug.

The Pinch event can't work

Here is my code:

render () {
    return (
      <div className="mapBox">
        <Hammer component="div" 
          onPinch = { this.pinchHandler.bind(this) }
          onRotate={ this.rotateHandler.bind(this) }
          options={ options }>
          <div id="svgMap" className="svg-map" style={ stype } ref="svgMap"></div>
        </Hammer>
      </div>
    )
}

but the pinchHandler and the rotateHandler don't run

is there have some question ?

Warning: Failed propType: Calling PropTypes validators directly is not supported by the `prop-types` package. Use `PropTypes.checkPropTypes()` to call them. Read more at http://fb.me/use-check-prop-types Check the render method of X

I'm using:

"react": "15.0.1",
"react-dom": "15.0.1",
"react-hammerjs": "1.0.1",

Everything works like a charm, but I get the following error in console:

Warning: Failed propType: Calling PropTypes validators directly is not supported 
by the `prop-types` package. Use `PropTypes.checkPropTypes()` to call them. 
Read more at http://fb.me/use-check-prop-types Check the render method of X

As described in above documentation:

You might be seeing this message because a component library has updated 
to use prop-types package, but your version of React is incompatible with it.

Got Weird Broken With React-Devtool

I use onPanMove to implement a drag feature and it works perfectly in mostly case.
But with React Devtool, the returned e.deltaX and e.deltaY become very strange (nearly out of document) and soon lose focus and trigger onPanEnd.

Im not sure what I encounter is a very special case or a common case :(

onPinchEnd support

Great work on this! Can you please also add PinchEnd support? I'm not a Git user so I can't contribute myself.

createClass is deprecated in React 15.5

As of React 15.5, createClass is deprecated, so using this library prints the following in the console:

Warning: Hammer: React.createClass is deprecated and will be removed in version 16. Use plain JavaScript classes instead. If you're not yet ready to migrate, create-react-class is available on npm as a drop-in replacement.

Hammer should either switch to using create-react-class or use plain JavaScript classes.

Doesn't work when used with server side rendering

Hammerjs troughs 'ReferenceError: window is not defined' when rendering React on the server. The problem seems to lie in the hammer.js wrapper.

react-hammerjs/node_modules/hammerjs/hammer.js:2463
})(window, document, 'Hammer');
ReferenceError: window is not defined

I use this as a quick fix in Hammer.js, but doubt if this is the right solution for this?

if (typeof window !== 'undefined') {
  var  Hammer = require('hammerjs');
}

Support for swipe left|right?

This is a fairly good component. Thank you very much!

I was wondering, how would I go if I wanted to implement onSwipeLeft for this component?

onPress not fired

below is the code I'm currently using, onPress seems not fired.
when I change onPress to onPan, everything works fine.
Is that a bug?

`

		<Hammer onSwipe={this.onSwipe}>  
			<div className="flex-column">  
				<div className="txt-ctrl">当前房间<br/><br/>xxxx 5幢 0602室 <em className="icon_down"></em></div>  
				<div className="flex2"></div>  
				<div className="ctrl-name">大门</div>  
				<Hammer className="btn-wrapper" onPress={this.onPress}>  
					<div>  
						<div id="v_locked" className="loc-wrapper locked"></div>  
						<div id="v_finger" className="loc-wrapper finger hide">  
							<img className="img_fingerprint" src="img/touch.gif" alt=""/>  
						</div>  
					</div>  
				</Hammer>  
				<div className="ctrl-name-small">长按1秒开锁</div>  
				<div className="flex1"></div>  
				<div className="flex1"></div>  
			</div>  
		</Hammer>

`

panstart support

At the moment listening for pan events won't allow you to detect when the panning has started since eventType doesn't pass through an INPUT_START.

It seems the typical approach would be to check the event.type field - see hammer #685. So a potential solution might be to change the pass event registration to if (this.props.onPan) this.hammer.on('panstart pan', this.props.onPan);, allowing React code to check the event.type field?

Cannot install with react 0.15

The value of peerDependencies is too restrictive as it pins React to ^0.14.3

$ npm install react-hammerjs --save
npm ERR! Darwin 15.3.0
npm ERR! argv "/Users/bramus/.nvm/versions/node/v4.3.1/bin/node" "/Users/bramus/.nvm/versions/node/v4.3.1/bin/npm" "install" "react-hammerjs" "--save"
npm ERR! node v4.3.1
npm ERR! npm  v2.14.12
npm ERR! code EPEERINVALID

npm ERR! peerinvalid The package [email protected] does not satisfy its siblings' peerDependencies requirements!
npm ERR! peerinvalid Peer [email protected] wants react@^15.0.1
npm ERR! peerinvalid Peer [email protected] wants react@^0.14.3

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/bramus/repos/protoplayer/npm-debug.log

swipe left/right

how do you set recognizers for onSwipe?

this isn't working for detecting swiperight

let options = { recognizers: { swipe: { event: 'swiperight' } } };

Warning property

I am getting a warning message when using the hammer component:

Warning: Unknown propoptionson <div> tag. Remove this prop from the element. For details, see https://fb.me/react-unknown-prop

gesture object and gesture.stopDetect() not available?

I may be going down the wrong path but so far as I can tell, the gesture experience I'm going for in more like this codepen, then like this one.

The first one is very responsive to swipes and pans. you can flick the slides back and forth very quickly. This is also very much like what the swiper lib can do. (seen on homepage)

When I dive into the the code of that ideal example, I can see that they are using gesture.stopDetect() in swipes to prevent pans.

I can't seem to find the gesture object anywhere in any of the events that react-hammerjs gives back.

In short, I really just want to reproduce that first example with my carousel in react and it seems like I may have to use native hammerjs to do so?

Feature Request: onPan and onPanMove

Hammer.js has both pan and panmove events.
pan handles panstart, panmove, and panend.
panmove handles only itself.

Can we have both onPan and onPanMove events?

Unable to load hammerjs

I am not sure about what I am doing wrong but some how the react-hammerjs module is unable to locate hammerjs

Just to be that hammerjs is installed I required it explicitly in my project and it was loading up

React hammer options not working for some properties

For example, if I'd like to set the default:

const hammerOptions = {
  cssProps: {
    userSelect: 'auto',
  },
};

This does not work. Seems like it may be because the code is using Hammer.set and these needs to be passed in the defaults.

Hammer swallowing child node ref

Was using...

     "react-dom": "^15.4.1",
     "react-hammerjs": "^0.5.0",

...and there was no issue.
Now I'm using..

    "react-dom": "^16.1.0",
    "react-hammerjs": "^1.0.1",

...and suddenly all children nodes to Hammer are being ignored.

EG. in the following code thing1 consoles but thing2 does NOT.

    return (
      <div ref={thing1 => { console.log('thing1', thing1) }}>
        <Hammer
          onPan={e => this.pan(e, theta, panelCount)}
          options={hammerOptions}
        >
          <div ref={thing2 => { console.log('thing2', thing2) }}>
            <div>{panels}</div>
          </div>
        </Hammer>
      </div>
    );

...removing Hammer completely allows thing2 to console.

Update Documentation or Expose Constants

Currently documentation seems to imply that constants are on the library:

import Hammer from 'react-hammerjs';

console.log(Hammer.DIRECTION_LEFT) //actually undefined
console.log(window.Hammer.DIRECTION_LEFT) //works

In any case, I would vote that the underlying Hammer object shouldn't be exposed globally and should be contained to the package.

onTap vs onTouchStart

Hi,

i was wondering if there is any difference between onTap and the builtin React onTouchStart ?

Conflicting versions of React, package.json suggestions

Hi there,

I am using React 0.13 beta on a small project and when I tried to pull react-hammer in, I had conflicting problems since I am using CommonJS with browserify and this allowed react-hammer to still use React 0.12 although my project is in 0.13. The end result is a mess of warnings and weird exceptions.

As far as I know, the best way to solve this is to move react on package.json from dependencies to peerDependencies and also making sure the supported versions are correct. So far, react-hammer is 100% compatible with react 0.13 as far as I tested.

If anyone else is having this problem, one workaround is to require the dist version directly. Here is how I am requiring react-hammer right now:

var Hammer = require('react-hammerjs/dist/react-hammerjs');

The drawback for this workaround is this will only work when React is global, which works for me since I already have --insert-global-vars React on my browserify configuration.

Use of deprecated React.PropTypes breaks in React v16

The Hammer component references React.PropTypes.string. However, accessing PropTypes from the react package is now deprecated and will break in React v16. Instead, PropTypes should be imported from the prop-types package.

Description of "direction" property in README is either wrong or misleading.

In the README, it says the following:

If you provide the prop direction the pan and swipe events will support Hammer.DIRECTION_(NONE/LEFT/RIGHT/UP/DOWN/HORIZONTAL/VERTICAL/ALL).

Reading this, the impression I get is that I can import the hammerjs library and supply any Hammer.DIRECTION_* value as the direction property on the react-hammerjs component. However, the direction property is actually expecting the property key for the constant, not the value of the constant itself.

For example:

import ReactHammer from 'react-hammerjs';
import Hammer from 'hammerjs';

// What I expected
<ReactHammer direction={Hammer.DIRECTION_ALL}><div></div></ReactHammer>

// What the library actually wanted
<ReactHammer direction="DIRECTION_ALL"><div></div></ReactHammer>

I would suggest that the documentation be updated to properly describe the direction property for pan and swipe events.

react-dom module dependency error

We have the following error after installing react-hammerjs (via npm):

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: Cannot find module 'react-dom' from '/root/project/as-intuit-table/node_modules/react-hammerjs/src'
    at /root/project/as-intuit-table/node_modules/browserify/node_modules/resolve/lib/async.js:46:17
    at process (/root/project/as-intuit-table/node_modules/browserify/node_modules/resolve/lib/async.js:173:43)
    at ondir (/root/project/as-intuit-table/node_modules/browserify/node_modules/resolve/lib/async.js:188:17)
    at load (/root/project/as-intuit-table/node_modules/browserify/node_modules/resolve/lib/async.js:69:43)
    at onex (/root/project/as-intuit-table/node_modules/browserify/node_modules/resolve/lib/async.js:92:31)
    at /root/project/as-intuit-table/node_modules/browserify/node_modules/resolve/lib/async.js:22:47
    at Object.oncomplete (fs.js:107:15)

Installing react-dom (0.14.0) fixes it.. but should it be in your deps?

Warning: Hammer: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop.

I'm using:

"react": "15.0.1",
"react-dom": "15.0.1",
"react-hammerjs": "1.0.1",

Everything works like a charm, but I get the following error in console:

Warning: Hammer: `ref` is not a prop. Trying to access it will result in `undefined` 
being returned. If you need to access the same value within the child component, 
you should pass it as a different prop.

I think that React deprecated string refs and now only supports callback refs.
https://facebook.github.io/react/docs/refs-and-the-dom.html#legacy-api-string-refs

Probably each instance of a string ref has to be updated to use a callback ref instead.

one hammer trigger another hammer

when i use react-hammerjs to build a single page web application, I found that when I wrote Hammer with props 'onTap' and and another Hammer behind. The second Hammer tirggered when I clicked the first Hammer , How can I prevent it, Thanks for every advice.

Customize hammerjs

The documentation does not make it clear, how to configure hammerjs, like

/* common hammerjs customization */
delete Hammer.defaults.cssProps.userSelect; // restore text highlight on desktop
Hammer.defaults.inputClass = Hammer.TouchInput; // only recognize gestures on touch inputs

How is it possible to to use react-hammerjs using this hammerjs config? Using options={{inputClass: 'Hammer.TouchInput'}}, as the documentation might suggest didn't work.

Suggestion: drop the `vertical` prop and replace it with a `direction` prop

I find the vertical prop somewhat confusing as it does not actually limit Hammer to vertical gestures, but to gestures in all directions.

From the code:

// Hammer.js, L53
    if (props.vertical) {
        hammer.get('pan').set({direction: Hammer.DIRECTION_ALL});
        hammer.get('swipe').set({direction: Hammer.DIRECTION_ALL});
    } else {
        hammer.get('pan').set({direction: Hammer.DIRECTION_HORIZONTAL});
        hammer.get('swipe').set({direction: Hammer.DIRECTION_HORIZONTAL});
    }

Given the Hammer.DIRECTION_* constants it'd be better to allow one to use those by means of a direction prop.

Example usage would be this:

var Hammer = require('hammerjs');
var ReactHammer = require('react-hammerjs');

<ReactHammer onSwipe={handleSwipe} direction="{Hammer.DIRECTION_VERTICAL}"><div>Swipe Me</div></ReactHammer>

(note that I also import Hammer itself, to gain access to the contstants. These could - for example - also be exposed on react-hammerjs)

Cannot be installed in React Native v0.44

I'm porting a React project to React Native v0.44 It says it cannot install the hammerjs dependency because the cap major version it allows is 15.x, however React Native 0.44 uses React 16.0.0-alpha.6. Do we know when 16 will be supported by hammerjs?

Error trying to use react-hammerjs with React 15.4.2

I'm trying to use react-hammerjs (0.5.0) with my react (15.4.2) app and I am getting the following error:

 Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in. Check the render method of `HammerMe`.
    at invariant (invariant.js:44)
    at ReactCompositeComponentWrapper.instantiateReactComponent [as _instantiateReactComponent] (instantiateReactComponent.js:77)
    at ReactCompositeComponentWrapper.performInitialMount (ReactCompositeComponent.js:367)
    at ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js:258)
    at Object.mountComponent (ReactReconciler.js:46)
    at ReactCompositeComponentWrapper.performInitialMount (ReactCompositeComponent.js:371)
    at ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js:258)
    at Object.mountComponent (ReactReconciler.js:46)
    at ReactCompositeComponentWrapper.performInitialMount (ReactCompositeComponent.js:371)
    at ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js:258)

Here is what my react component looks like:

import React from 'react';
import { Hammer } from 'react-hammerjs';

class HammerMe extends React.Component {
	
	handleTap(e) {
		console.log('Tap', e);
	}
    
    render() {
        return (
            <Hammer onTap={this.handleTap}> <div>Tap Me</div></Hammer>
        );
    }
}

export default HammerMe;

About requireFailure?

mc.get('doubletap').recognizeWith('singletap');
mc.get('singletap').requireFailure('doubletap');

Hey I just want to do the above in react with this package, but I couldn't found a way. Any idea how I can manage this?

The actual problem is when you bind both onTap and onDoubleTap onTap fires first before onDoubleTap any other solution also works for me.

stopPropagation is not stopping events from bubble up

I have a child element using onTap and a parent element using onTap as well. But seems the stopPropagation for both is not seems stopping the event from firing, both function has the stopPropagation are firing regardless... any fix or clue?

Uncaught TypeError on load

Hello, when loading the page I get a type error:

screen shot 2015-10-08 at 7 49 46 pm

This references:
screen shot 2015-10-08 at 7 50 00 pm

I have tried verifying this.actions is a string, but no luck. Is there any reason why I am getting this error? I would assume that it's something I just am overlooking. Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.