0
# React Swipeable
1
2
React Swipeable is a React hook that provides comprehensive swipe gesture detection for touch devices and mouse interactions. It offers directional swipe callbacks, customizable sensitivity settings, velocity calculations, and supports both touch and mouse events with minimal performance impact.
3
4
## Package Information
5
6
- **Package Name**: react-swipeable
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install react-swipeable`
10
11
## Core Imports
12
13
```typescript
14
import { useSwipeable } from "react-swipeable";
15
```
16
17
Import with types:
18
19
```typescript
20
import { useSwipeable, SwipeableProps, SwipeEventData, LEFT, RIGHT, UP, DOWN } from "react-swipeable";
21
```
22
23
For CommonJS:
24
25
```javascript
26
const { useSwipeable } = require("react-swipeable");
27
```
28
29
## Basic Usage
30
31
```typescript
32
import { useSwipeable } from "react-swipeable";
33
34
function SwipeExample() {
35
const handlers = useSwipeable({
36
onSwiped: (eventData) => console.log("User swiped!", eventData),
37
onSwipedLeft: () => console.log("User swiped left!"),
38
onSwipedRight: () => console.log("User swiped right!"),
39
preventScrollOnSwipe: true,
40
trackMouse: true
41
});
42
43
return <div {...handlers}>Swipe me!</div>;
44
}
45
```
46
47
## Architecture
48
49
React Swipeable is built around a single React hook that follows these key patterns:
50
51
- **Hook Pattern**: `useSwipeable` hook returns event handlers to attach to target elements
52
- **Event System**: Handles both touch events (mobile) and mouse events (desktop) uniformly
53
- **State Management**: Internal state tracking for gesture lifecycle (start, move, end)
54
- **Performance**: Uses passive event listeners by default for smooth scrolling
55
- **Type Safety**: Full TypeScript support with comprehensive type definitions
56
57
## Capabilities
58
59
### Swipeable Hook
60
61
The main hook for detecting and handling swipe gestures on React elements.
62
63
```typescript { .api }
64
/**
65
* React hook for handling swipe gestures on touch devices and mouse interactions
66
* @param options - Configuration and callback options
67
* @returns Event handlers to spread onto target element
68
*/
69
function useSwipeable(options: SwipeableProps): SwipeableHandlers;
70
71
interface SwipeableHandlers {
72
/** Ref callback to attach to target element */
73
ref(element: HTMLElement | null): void;
74
/** Optional mouse down handler (present when trackMouse is true) */
75
onMouseDown?(event: React.MouseEvent): void;
76
}
77
```
78
79
### Configuration Options
80
81
All configuration options for customizing swipe behavior.
82
83
```typescript { .api }
84
interface SwipeableProps {
85
// Event Callbacks
86
/** Called at start of a tracked swipe */
87
onSwipeStart?: SwipeCallback;
88
/** Called for each move event during a tracked swipe */
89
onSwiping?: SwipeCallback;
90
/** Called after any swipe */
91
onSwiped?: SwipeCallback;
92
/** Called after a LEFT swipe */
93
onSwipedLeft?: SwipeCallback;
94
/** Called after a RIGHT swipe */
95
onSwipedRight?: SwipeCallback;
96
/** Called after a UP swipe */
97
onSwipedUp?: SwipeCallback;
98
/** Called after a DOWN swipe */
99
onSwipedDown?: SwipeCallback;
100
/** Called after a tap (touch under min distance) */
101
onTap?: TapCallback;
102
/** Called for touchstart and mousedown events */
103
onTouchStartOrOnMouseDown?: TapCallback;
104
/** Called for touchend and mouseup events */
105
onTouchEndOrOnMouseUp?: TapCallback;
106
107
// Configuration Options
108
/** Min distance (px) before a swipe starts. Default: 10 */
109
delta?: number | { [key in Lowercase<SwipeDirections>]?: number };
110
/** Prevents scroll during swipe in most cases. Default: false */
111
preventScrollOnSwipe?: boolean;
112
/** Set a rotation angle for coordinate system. Default: 0 */
113
rotationAngle?: number;
114
/** Track mouse input. Default: false */
115
trackMouse?: boolean;
116
/** Track touch input. Default: true */
117
trackTouch?: boolean;
118
/** Allowable duration of a swipe (ms). Default: Infinity */
119
swipeDuration?: number;
120
/** Options for touch event listeners. Default: { passive: true } */
121
touchEventOptions?: { passive: boolean };
122
}
123
```
124
125
### Event Data
126
127
Data provided to swipe event callbacks containing comprehensive gesture information.
128
129
```typescript { .api }
130
interface SwipeEventData {
131
/** Absolute displacement of swipe in x direction */
132
absX: number;
133
/** Absolute displacement of swipe in y direction */
134
absY: number;
135
/** Displacement of swipe in x direction (current.x - initial.x) */
136
deltaX: number;
137
/** Displacement of swipe in y direction (current.y - initial.y) */
138
deltaY: number;
139
/** Direction of swipe - Left | Right | Up | Down */
140
dir: SwipeDirections;
141
/** Source event object */
142
event: HandledEvents;
143
/** True for the first event of a tracked swipe */
144
first: boolean;
145
/** Location where swipe started - [x, y] */
146
initial: Vector2;
147
/** Absolute velocity (speed) - √(absX² + absY²) / time */
148
velocity: number;
149
/** Velocity per axis - [deltaX/time, deltaY/time] */
150
vxvy: Vector2;
151
}
152
```
153
154
### Callback Types
155
156
Function signatures for swipe and tap event callbacks.
157
158
```typescript { .api }
159
/** Callback function for swipe events */
160
type SwipeCallback = (eventData: SwipeEventData) => void;
161
162
/** Callback function for tap events */
163
type TapCallback = ({ event }: { event: HandledEvents }) => void;
164
165
/** Interface containing all directional swipe callbacks */
166
interface SwipeableDirectionCallbacks {
167
/** Called after a DOWN swipe */
168
onSwipedDown?: SwipeCallback;
169
/** Called after a LEFT swipe */
170
onSwipedLeft?: SwipeCallback;
171
/** Called after a RIGHT swipe */
172
onSwipedRight?: SwipeCallback;
173
/** Called after a UP swipe */
174
onSwipedUp?: SwipeCallback;
175
}
176
```
177
178
### Direction Constants
179
180
Constants for swipe directions.
181
182
```typescript { .api }
183
/** Left swipe direction constant */
184
const LEFT = "Left";
185
186
/** Right swipe direction constant */
187
const RIGHT = "Right";
188
189
/** Up swipe direction constant */
190
const UP = "Up";
191
192
/** Down swipe direction constant */
193
const DOWN = "Down";
194
195
/** Union type for all swipe directions */
196
type SwipeDirections = typeof LEFT | typeof RIGHT | typeof UP | typeof DOWN;
197
```
198
199
### Utility Types
200
201
Additional utility types used by the library.
202
203
```typescript { .api }
204
/** Two-dimensional vector for coordinates */
205
type Vector2 = [number, number];
206
207
/** Event types handled by the library */
208
type HandledEvents = React.MouseEvent | TouchEvent | MouseEvent;
209
```
210
211
## Usage Examples
212
213
### Basic Directional Callbacks
214
215
```typescript
216
import { useSwipeable } from "react-swipeable";
217
218
function ImageCarousel() {
219
const [currentIndex, setCurrentIndex] = useState(0);
220
221
const handlers = useSwipeable({
222
onSwipedLeft: () => setCurrentIndex(prev => prev + 1),
223
onSwipedRight: () => setCurrentIndex(prev => prev - 1),
224
preventScrollOnSwipe: true,
225
trackMouse: true
226
});
227
228
return <div {...handlers}>Image content here</div>;
229
}
230
```
231
232
### Advanced Configuration with Event Data
233
234
```typescript
235
import { useSwipeable, SwipeEventData } from "react-swipeable";
236
237
function AdvancedSwipeHandler() {
238
const handlers = useSwipeable({
239
onSwiping: (eventData: SwipeEventData) => {
240
// Track swipe progress
241
console.log(`Swiping ${eventData.dir}: ${eventData.absX}px, ${eventData.absY}px`);
242
console.log(`Velocity: ${eventData.velocity}`);
243
},
244
onSwiped: (eventData: SwipeEventData) => {
245
// Handle completed swipe
246
if (eventData.velocity > 0.5) {
247
console.log("Fast swipe detected!");
248
}
249
},
250
delta: { left: 50, right: 50, up: 20, down: 20 }, // Different thresholds per direction
251
swipeDuration: 1000, // Maximum 1 second swipes
252
preventScrollOnSwipe: true,
253
trackMouse: true
254
});
255
256
return <div {...handlers}>Advanced swipe area</div>;
257
}
258
```
259
260
### Mobile Navigation Menu
261
262
```typescript
263
import { useSwipeable } from "react-swipeable";
264
265
function MobileNav({ isOpen, onToggle }: { isOpen: boolean; onToggle: (open: boolean) => void }) {
266
const handlers = useSwipeable({
267
onSwipedLeft: () => onToggle(false), // Close menu
268
onSwipedRight: () => onToggle(true), // Open menu
269
trackTouch: true,
270
trackMouse: false, // Touch only for mobile
271
preventScrollOnSwipe: true,
272
delta: 30 // Require 30px minimum swipe
273
});
274
275
return (
276
<div {...handlers} className={`nav-menu ${isOpen ? 'open' : 'closed'}`}>
277
Navigation content
278
</div>
279
);
280
}
281
```
282
283
### Touch-enabled Game Controls
284
285
```typescript
286
import { useSwipeable, LEFT, RIGHT, UP, DOWN } from "react-swipeable";
287
288
function GameControls({ onMove }: { onMove: (direction: string) => void }) {
289
const handlers = useSwipeable({
290
onSwipedLeft: () => onMove(LEFT),
291
onSwipedRight: () => onMove(RIGHT),
292
onSwipedUp: () => onMove(UP),
293
onSwipedDown: () => onMove(DOWN),
294
onTap: () => console.log("Tap detected - maybe pause?"),
295
delta: 20,
296
swipeDuration: 500, // Quick swipes only
297
preventScrollOnSwipe: true,
298
trackMouse: true // Support both touch and mouse
299
});
300
301
return <div {...handlers} className="game-controls">Game area</div>;
302
}
303
```