Browse Source

Add pointer events example

main
Andrew Clark 7 years ago
parent
commit
55b251146d
  1. 2
      content/blog/2018-05-23-react-v-16-4.md
  2. 95
      examples/16-4-release-blog-post/pointer-events-example.js

2
content/blog/2018-05-23-react-v-16-4.md

@ -24,6 +24,8 @@ The following event types are now available in React DOM:
Please note that these events will only work in browsers that support the Pointer Events specification. (At the time of this writing, this includes the latest versions of Chrome, Firefox, Edge, and Internet Explorer.) If your application depends on pointer events, we recommend using a third-party pointer events polyfill. We have opted not to include such a polyfill in React DOM, to avoid an increase in bundle size.
[Check out this example on CodeSandbox.](codesandbox://16-4-release-blog-post/pointer-events-example)
Huge thanks to [Philip Spiess](https://github.com/philipp-spiess) for contributing this change!
## Bugfix for `getDerivedStateFromProps`

95
examples/16-4-release-blog-post/pointer-events-example.js

@ -0,0 +1,95 @@
import React from 'react';
import ReactDOM from 'react-dom';
const CIRCLE_SIZE = 80;
class DragBox extends React.Component {
state = {
hasCapture: false,
circleLeft: 80,
circleTop: 80,
};
isDragging = false;
previousLeft = 0;
previousTop = 0;
onDown = event => {
this.isDragging = true;
event.target.setPointerCapture(event.pointerId);
// We store the initial coordinates to be able to calculate the changes
// later on.
this.extractPositionDelta(event);
};
onMove = event => {
if (!this.isDragging) {
return;
}
const {left, top} = this.extractPositionDelta(event);
this.setState(({circleLeft, circleTop}) => ({
circleLeft: circleLeft + left,
circleTop: circleTop + top,
}));
};
onUp = event => (this.isDragging = false);
onGotCapture = event => this.setState({hasCapture: true});
onLostCapture = event =>
this.setState({hasCapture: false});
extractPositionDelta = event => {
const left = event.pageX;
const top = event.pageY;
const delta = {
left: left - this.previousLeft,
top: top - this.previousTop,
};
this.previousLeft = left;
this.previousTop = top;
return delta;
};
render() {
const {hasCapture, circleLeft, circleTop} = this.state;
const boxStyle = {
border: '1px solid #d9d9d9',
margin: '10px 0 20px',
minHeight: 400,
width: '100%',
position: 'relative',
};
const circleStyle = {
width: CIRCLE_SIZE,
height: CIRCLE_SIZE,
borderRadius: CIRCLE_SIZE / 2,
position: 'absolute',
left: circleLeft,
top: circleTop,
backgroundColor: hasCapture ? 'blue' : 'green',
touchAction: 'none',
};
return (
<div style={boxStyle}>
<div
style={circleStyle}
onPointerDown={this.onDown}
onPointerMove={this.onMove}
onPointerUp={this.onUp}
onPointerCancel={this.onUp}
onGotPointerCapture={this.onGotCapture}
onLostPointerCapture={this.onLostCapture}
/>
</div>
);
}
}
ReactDOM.render(
<DragBox />,
document.getElementById('root')
);
Loading…
Cancel
Save