├── .github └── workflows │ └── test.yml ├── .gitignore ├── .npmrc ├── CONTRIBUTING.md ├── LICENSE ├── demo.gif ├── index.d.ts ├── index.js ├── index.native.js ├── package.json ├── readme.md └── useWindowSize.js /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Node CI 2 | 3 | on: 4 | pull_request: 5 | branches: 6 | - master 7 | 8 | jobs: 9 | build: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v2 13 | - name: Install Node.js 14 | uses: actions/setup-node@v1 15 | with: 16 | node-version: 12.16.3 17 | - name: Install dependencies 18 | run: npm install 19 | - name: Run tests 20 | run: npm test 21 | env: 22 | CI: true 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /node_modules/ 2 | 3 | #Visual Studio Code 4 | .vscode 5 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | package-lock=false 2 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Welcome to React Tinder Card contributing guide 2 | 3 | Thank you for investing your time in contributing to my project! PRs are welcome but make sure to follow the rules listed in this guide. 4 | 5 | ## Rules 6 | 7 | ### 1. Only include ONE new feature in each PR. 8 | 9 | If you have multiple improvements please submit multiple independent PRs. 10 | 11 | ### 2. The code has to be backward compatible. 12 | 13 | This repository has a large userbase and we do not want any breaking changes. That means do not change the name or arguments of the original functions. If you have a good reason for making a breaking change please clearly state that in your PR. 14 | 15 | ### 3. Always make the same change to both the React code as well as the React Native code. 16 | 17 | This module is compatible with both React as well as React Native. While the code is different the props and API are identical. I will not merge any PRs that split the props and API. 18 | 19 | ### 4. Make sure your code passes ```npm run test```. 20 | 21 | The test script will automatically generate props to the readme using `ts-readme-generator` and check that the code is formatted using standard. Read more about standard JS [here](https://standardjs.com). 22 | 23 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019-2021 Jakob Unnebäck 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/3DJakob/react-tinder-card/b6125689aa9d098f23f7b44b7fb17e489c8dabbe/demo.gif -------------------------------------------------------------------------------- /index.d.ts: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | 3 | declare type Direction = 'left' | 'right' | 'up' | 'down' 4 | declare type SwipeHandler = (direction: Direction) => void 5 | declare type CardLeftScreenHandler = (direction: Direction) => void 6 | declare type SwipeRequirementFufillUpdate = (direction: Direction) => void 7 | declare type SwipeRequirementUnfufillUpdate = () => void 8 | 9 | declare interface API { 10 | /** 11 | * Programmatically trigger a swipe of the card in one of the valid directions `'left'`, `'right'`, `'up'` and `'down'`. This function, `swipe`, can be called on a reference of the TinderCard instance. Check the [example](https://github.com/3DJakob/react-tinder-card-demo/blob/master/src/examples/Advanced.js) code for more details on how to use this. 12 | * 13 | * @param dir The direction in which the card should be swiped. One of: `'left'`, `'right'`, `'up'` and `'down'`. 14 | */ 15 | swipe(dir?: Direction): Promise 16 | 17 | /** 18 | * Restore swiped-card state. Use this function if you want to undo a swiped-card (e.g. you have a back button that shows last swiped card or you have a reset button. The promise is resolved once the card is returned 19 | */ 20 | restoreCard (): Promise 21 | } 22 | 23 | declare interface Props { 24 | ref?: React.Ref 25 | 26 | /** 27 | * Whether or not to let the element be flicked away off-screen after a swipe. 28 | * 29 | * @default true 30 | */ 31 | flickOnSwipe?: boolean 32 | 33 | /** 34 | * Callback that will be executed when a swipe has been completed. It will be called with a single string denoting which direction the swipe was in: `'left'`, `'right'`, `'up'` or `'down'`. 35 | */ 36 | onSwipe?: SwipeHandler 37 | 38 | /** 39 | * Callback that will be executed when a `TinderCard` has left the screen. It will be called with a single string denoting which direction the swipe was in: `'left'`, `'right'`, `'up'` or `'down'`. 40 | */ 41 | onCardLeftScreen?: CardLeftScreenHandler 42 | 43 | /** 44 | * An array of directions for which to prevent swiping out of screen. Valid arguments are `'left'`, `'right'`, `'up'` and `'down'`. 45 | * 46 | * @default [] 47 | */ 48 | preventSwipe?: string[] 49 | 50 | /** 51 | * What method to evaluate what direction to throw the card on release. 'velocity' will evaluate direction based on the direction of the swiping movement. 'position' will evaluate direction based on the position the card has on the screen like in the app tinder. 52 | * If set to position it is recommended to manually set swipeThreshold based on the screen size as not all devices will accommodate the default distance of 300px and the default native swipeThreshold is 1px which most likely is undesirably low. 53 | * 54 | * @default 'velocity' 55 | */ 56 | swipeRequirementType?: 'velocity' | 'position' 57 | 58 | /** 59 | * The threshold of which to accept swipes. If swipeRequirementType is set to velocity it is the velocity threshold and if set to position it is the position threshold. 60 | * On native the default value is 1 as the physics works differently there. 61 | * If swipeRequirementType is set to position it is recommended to set this based on the screen width so cards can be swiped on all screen sizes. 62 | * 63 | * @default 300 64 | */ 65 | swipeThreshold?: number 66 | 67 | /** 68 | * Callback that will be executed when a `TinderCard` has fulfilled the requirement necessary to be swiped in a direction on release. This in combination with `onSwipeRequirementUnfulfilled` is useful for displaying user feedback on the card. When using this it is recommended to use `swipeRequirementType='position'` as this will fire a lot otherwise. 69 | * It will be called with a single string denoting which direction the user is swiping: `'left'`, `'right'`, `'up'` or `'down'`. 70 | */ 71 | onSwipeRequirementFulfilled?: SwipeRequirementFufillUpdate 72 | 73 | /** 74 | * Callback that will be executed when a `TinderCard` has unfulfilled the requirement necessary to be swiped in a direction on release. 75 | */ 76 | onSwipeRequirementUnfulfilled?: SwipeRequirementUnfufillUpdate 77 | 78 | /** 79 | * HTML attribute class 80 | */ 81 | className?: string 82 | 83 | /** 84 | * The children passed in is what will be rendered as the actual Tinder-style card. 85 | */ 86 | children?: React.ReactNode 87 | } 88 | 89 | declare const TinderCard: React.FC 90 | 91 | export = TinderCard 92 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | const React = require('react') 2 | const { useSpring, animated } = require('@react-spring/web') 3 | const useWindowSize = require('./useWindowSize') 4 | 5 | const settings = { 6 | maxTilt: 25, // in deg 7 | rotationPower: 50, 8 | swipeThreshold: 0.5 // need to update this threshold for RN (1.5 seems reasonable...?) 9 | } 10 | 11 | // physical properties of the spring 12 | const physics = { 13 | touchResponsive: { 14 | friction: 50, 15 | tension: 2000 16 | }, 17 | animateOut: { 18 | friction: 30, 19 | tension: 400 20 | }, 21 | animateBack: { 22 | friction: 10, 23 | tension: 200 24 | } 25 | } 26 | 27 | const pythagoras = (x, y) => { 28 | return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)) 29 | } 30 | 31 | const normalize = (vector) => { 32 | const length = Math.sqrt(Math.pow(vector.x, 2) + Math.pow(vector.y, 2)) 33 | return { x: vector.x / length, y: vector.y / length } 34 | } 35 | 36 | const animateOut = async (gesture, setSpringTarget, windowHeight, windowWidth) => { 37 | const diagonal = pythagoras(windowHeight, windowWidth) 38 | const velocity = pythagoras(gesture.x, gesture.y) 39 | const finalX = diagonal * gesture.x 40 | const finalY = diagonal * gesture.y 41 | const finalRotation = gesture.x * 45 42 | const duration = diagonal / velocity 43 | 44 | setSpringTarget.start({ 45 | xyrot: [finalX, finalY, finalRotation], 46 | config: { duration: duration } 47 | }) 48 | 49 | // for now animate back 50 | return await new Promise((resolve) => 51 | setTimeout(() => { 52 | resolve() 53 | }, duration) 54 | ) 55 | } 56 | 57 | const animateBack = (setSpringTarget) => { 58 | // translate back to the initial position 59 | return new Promise((resolve) => { 60 | setSpringTarget.start({ xyrot: [0, 0, 0], config: physics.animateBack, onRest: resolve }) 61 | }) 62 | } 63 | 64 | const getSwipeDirection = (property) => { 65 | if (Math.abs(property.x) > Math.abs(property.y)) { 66 | if (property.x > settings.swipeThreshold) { 67 | return 'right' 68 | } else if (property.x < -settings.swipeThreshold) { 69 | return 'left' 70 | } 71 | } else { 72 | if (property.y > settings.swipeThreshold) { 73 | return 'down' 74 | } else if (property.y < -settings.swipeThreshold) { 75 | return 'up' 76 | } 77 | } 78 | return 'none' 79 | } 80 | 81 | // must be created outside of the TinderCard forwardRef 82 | const AnimatedDiv = animated.div 83 | 84 | const TinderCard = React.forwardRef( 85 | ( 86 | { flickOnSwipe = true, children, onSwipe, onCardLeftScreen, className, preventSwipe = [], swipeRequirementType = 'velocity', swipeThreshold = settings.swipeThreshold, onSwipeRequirementFulfilled, onSwipeRequirementUnfulfilled }, 87 | ref 88 | ) => { 89 | const { width, height } = useWindowSize() 90 | const [{ xyrot }, setSpringTarget] = useSpring(() => ({ 91 | xyrot: [0, 0, 0], 92 | config: physics.touchResponsive 93 | })) 94 | 95 | settings.swipeThreshold = swipeThreshold 96 | 97 | React.useImperativeHandle(ref, () => ({ 98 | async swipe (dir = 'right') { 99 | if (onSwipe) onSwipe(dir) 100 | const power = 1.3 101 | const disturbance = (Math.random() - 0.5) / 2 102 | if (dir === 'right') { 103 | await animateOut({ x: power, y: disturbance }, setSpringTarget, width, height) 104 | } else if (dir === 'left') { 105 | await animateOut({ x: -power, y: disturbance }, setSpringTarget, width, height) 106 | } else if (dir === 'up') { 107 | await animateOut({ x: disturbance, y: -power }, setSpringTarget, width, height) 108 | } else if (dir === 'down') { 109 | await animateOut({ x: disturbance, y: power }, setSpringTarget, width, height) 110 | } 111 | if (onCardLeftScreen) onCardLeftScreen(dir) 112 | }, 113 | async restoreCard () { 114 | await animateBack(setSpringTarget) 115 | } 116 | })) 117 | 118 | const handleSwipeReleased = React.useCallback( 119 | async (setSpringTarget, gesture) => { 120 | // Check if this is a swipe 121 | const dir = getSwipeDirection({ 122 | x: swipeRequirementType === 'velocity' ? gesture.vx : gesture.dx, 123 | y: swipeRequirementType === 'velocity' ? gesture.vy : gesture.dy 124 | }) 125 | 126 | if (dir !== 'none') { 127 | if (flickOnSwipe) { 128 | if (!preventSwipe.includes(dir)) { 129 | if (onSwipe) onSwipe(dir) 130 | 131 | await animateOut(swipeRequirementType === 'velocity' ? ({ 132 | x: gesture.vx, 133 | y: gesture.vy 134 | }) : ( 135 | normalize({ x: gesture.dx, y: gesture.dy }) // Normalize to avoid flicking the card away with super fast speed only direction is wanted here 136 | ), setSpringTarget, width, height) 137 | if (onCardLeftScreen) onCardLeftScreen(dir) 138 | return 139 | } 140 | } 141 | } 142 | 143 | // Card was not flicked away, animate back to start 144 | animateBack(setSpringTarget) 145 | }, 146 | [swipeRequirementType, flickOnSwipe, preventSwipe, onSwipe, onCardLeftScreen, width, height] 147 | ) 148 | 149 | let swipeThresholdFulfilledDirection = 'none' 150 | 151 | const gestureStateFromWebEvent = (ev, startPositon, lastPosition, isTouch) => { 152 | let dx = isTouch ? ev.touches[0].clientX - startPositon.x : ev.clientX - startPositon.x 153 | let dy = isTouch ? ev.touches[0].clientY - startPositon.y : ev.clientY - startPositon.y 154 | 155 | // We cant calculate velocity from the first event 156 | if (startPositon.x === 0 && startPositon.y === 0) { 157 | dx = 0 158 | dy = 0 159 | } 160 | 161 | const vx = -(dx - lastPosition.dx) / (lastPosition.timeStamp - Date.now()) 162 | const vy = -(dy - lastPosition.dy) / (lastPosition.timeStamp - Date.now()) 163 | 164 | const gestureState = { dx, dy, vx, vy, timeStamp: Date.now() } 165 | return gestureState 166 | } 167 | 168 | React.useLayoutEffect(() => { 169 | let startPositon = { x: 0, y: 0 } 170 | let lastPosition = { dx: 0, dy: 0, vx: 0, vy: 0, timeStamp: Date.now() } 171 | let isClicking = false 172 | 173 | const onTouchStart = (ev) => { 174 | if (!ev.srcElement.className.includes('pressable') && ev.cancelable) { 175 | ev.preventDefault() 176 | } 177 | 178 | const gestureState = gestureStateFromWebEvent(ev, startPositon, lastPosition, true) 179 | lastPosition = gestureState 180 | startPositon = { x: ev.touches[0].clientX, y: ev.touches[0].clientY } 181 | } 182 | 183 | element.current.addEventListener(('touchstart'), onTouchStart) 184 | 185 | const onMouseDown = (ev) => { 186 | isClicking = true 187 | const gestureState = gestureStateFromWebEvent(ev, startPositon, lastPosition, false) 188 | lastPosition = gestureState 189 | startPositon = { x: ev.clientX, y: ev.clientY } 190 | } 191 | 192 | element.current.addEventListener(('mousedown'), onMouseDown) 193 | 194 | const handleMove = (gestureState) => { 195 | // Check fulfillment 196 | if (onSwipeRequirementFulfilled || onSwipeRequirementUnfulfilled) { 197 | const dir = getSwipeDirection({ 198 | x: swipeRequirementType === 'velocity' ? gestureState.vx : gestureState.dx, 199 | y: swipeRequirementType === 'velocity' ? gestureState.vy : gestureState.dy 200 | }) 201 | if (dir !== swipeThresholdFulfilledDirection) { 202 | swipeThresholdFulfilledDirection = dir 203 | if (swipeThresholdFulfilledDirection === 'none') { 204 | if (onSwipeRequirementUnfulfilled) onSwipeRequirementUnfulfilled() 205 | } else { 206 | if (onSwipeRequirementFulfilled) onSwipeRequirementFulfilled(dir) 207 | } 208 | } 209 | } 210 | 211 | // use guestureState.vx / guestureState.vy for velocity calculations 212 | // translate element 213 | let rot = gestureState.vx * 15 // Magic number 15 looks about right 214 | if (isNaN(rot)) rot = 0 215 | rot = Math.max(Math.min(rot, settings.maxTilt), -settings.maxTilt) 216 | setSpringTarget.start({ xyrot: [gestureState.dx, gestureState.dy, rot], config: physics.touchResponsive }) 217 | } 218 | 219 | const onMouseMove = (ev) => { 220 | if (!isClicking) return 221 | const gestureState = gestureStateFromWebEvent(ev, startPositon, lastPosition, false) 222 | lastPosition = gestureState 223 | handleMove(gestureState) 224 | } 225 | 226 | window.addEventListener(('mousemove'), onMouseMove) 227 | 228 | const onMouseUp = (ev) => { 229 | if (!isClicking) return 230 | isClicking = false 231 | handleSwipeReleased(setSpringTarget, lastPosition) 232 | startPositon = { x: 0, y: 0 } 233 | lastPosition = { dx: 0, dy: 0, vx: 0, vy: 0, timeStamp: Date.now() } 234 | } 235 | 236 | window.addEventListener(('mouseup'), onMouseUp) 237 | 238 | const onTouchMove = (ev) => { 239 | const gestureState = gestureStateFromWebEvent(ev, startPositon, lastPosition, true) 240 | lastPosition = gestureState 241 | handleMove(gestureState) 242 | } 243 | 244 | element.current.addEventListener(('touchmove'), onTouchMove) 245 | 246 | const onTouchEnd = (ev) => { 247 | handleSwipeReleased(setSpringTarget, lastPosition) 248 | startPositon = { x: 0, y: 0 } 249 | lastPosition = { dx: 0, dy: 0, vx: 0, vy: 0, timeStamp: Date.now() } 250 | } 251 | 252 | element.current.addEventListener(('touchend'), onTouchEnd) 253 | 254 | return () => { 255 | element.current.removeEventListener(('touchstart'), onTouchStart) 256 | element.current.removeEventListener(('touchmove'), onTouchMove) 257 | element.current.removeEventListener(('touchend'), onTouchEnd) 258 | window.removeEventListener(('mousemove'), onMouseMove) 259 | window.removeEventListener(('mouseup'), onMouseUp) 260 | element.current.removeEventListener(('mousedown'), onMouseDown) 261 | } 262 | }, [handleSwipeReleased, setSpringTarget, onSwipeRequirementFulfilled, onSwipeRequirementUnfulfilled]) 263 | 264 | const element = React.useRef() 265 | 266 | return ( 267 | React.createElement(AnimatedDiv, { 268 | ref: element, 269 | className, 270 | style: { 271 | transform: xyrot.to((x, y, rot) => `translate3d(${x}px, ${y}px, ${0}px) rotate(${rot}deg)`) 272 | }, 273 | children 274 | }) 275 | ) 276 | } 277 | ) 278 | 279 | module.exports = TinderCard 280 | -------------------------------------------------------------------------------- /index.native.js: -------------------------------------------------------------------------------- 1 | const React = require('react') 2 | const { View, PanResponder, Dimensions } = require('react-native') 3 | const { useSpring, animated } = require('@react-spring/native') 4 | const { height, width } = Dimensions.get('window') 5 | 6 | const settings = { 7 | maxTilt: 25, // in deg 8 | rotationPower: 50, 9 | swipeThreshold: 1 // need to update this threshold for RN (1.5 seems reasonable...?) 10 | } 11 | 12 | // physical properties of the spring 13 | const physics = { 14 | touchResponsive: { 15 | friction: 50, 16 | tension: 2000 17 | }, 18 | animateOut: { 19 | friction: 30, 20 | tension: 400 21 | }, 22 | animateBack: { 23 | friction: 10, 24 | tension: 200 25 | } 26 | } 27 | 28 | const pythagoras = (x, y) => { 29 | return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)) 30 | } 31 | 32 | const normalize = (vector) => { 33 | const length = Math.sqrt(Math.pow(vector.x, 2) + Math.pow(vector.y, 2)) 34 | return { x: vector.x / length, y: vector.y / length } 35 | } 36 | 37 | const animateOut = async (gesture, setSpringTarget) => { 38 | const diagonal = pythagoras(height, width) 39 | const velocity = pythagoras(gesture.x, gesture.y) 40 | const finalX = diagonal * gesture.x 41 | const finalY = diagonal * gesture.y 42 | const finalRotation = gesture.x * 45 43 | const duration = diagonal / velocity 44 | 45 | setSpringTarget.current[0].start({ 46 | x: finalX, 47 | y: finalY, 48 | rot: finalRotation, // set final rotation value based on gesture.vx 49 | config: { duration: duration } 50 | }) 51 | 52 | // for now animate back 53 | return await new Promise((resolve) => 54 | setTimeout(() => { 55 | resolve() 56 | }, duration) 57 | ) 58 | } 59 | 60 | const animateBack = (setSpringTarget) => { 61 | // translate back to the initial position 62 | return new Promise((resolve) => { 63 | setSpringTarget.current[0].start({ x: 0, y: 0, rot: 0, config: physics.animateBack, onRest: resolve }) 64 | }) 65 | } 66 | 67 | const getSwipeDirection = (property) => { 68 | if (Math.abs(property.x) > Math.abs(property.y)) { 69 | if (property.x > settings.swipeThreshold) { 70 | return 'right' 71 | } else if (property.x < -settings.swipeThreshold) { 72 | return 'left' 73 | } 74 | } else { 75 | if (property.y > settings.swipeThreshold) { 76 | return 'down' 77 | } else if (property.y < -settings.swipeThreshold) { 78 | return 'up' 79 | } 80 | } 81 | return 'none' 82 | } 83 | 84 | // must be created outside of the TinderCard forwardRef 85 | const AnimatedView = animated(View) 86 | 87 | const TinderCard = React.forwardRef( 88 | ( 89 | { flickOnSwipe = true, children, onSwipe, onCardLeftScreen, className, preventSwipe = [], swipeRequirementType = 'velocity', swipeThreshold = settings.swipeThreshold, onSwipeRequirementFulfilled, onSwipeRequirementUnfulfilled }, 90 | ref 91 | ) => { 92 | const [{ x, y, rot }, setSpringTarget] = useSpring(() => ({ 93 | x: 0, 94 | y: 0, 95 | rot: 0, 96 | config: physics.touchResponsive 97 | })) 98 | settings.swipeThreshold = swipeThreshold 99 | 100 | React.useImperativeHandle(ref, () => ({ 101 | async swipe (dir = 'right') { 102 | if (onSwipe) onSwipe(dir) 103 | const power = 1.3 104 | const disturbance = (Math.random() - 0.5) / 2 105 | if (dir === 'right') { 106 | await animateOut({ x: power, y: disturbance }, setSpringTarget) 107 | } else if (dir === 'left') { 108 | await animateOut({ x: -power, y: disturbance }, setSpringTarget) 109 | } else if (dir === 'up') { 110 | await animateOut({ x: disturbance, y: -power }, setSpringTarget) 111 | } else if (dir === 'down') { 112 | await animateOut({ x: disturbance, y: power }, setSpringTarget) 113 | } 114 | if (onCardLeftScreen) onCardLeftScreen(dir) 115 | }, 116 | async restoreCard () { 117 | await animateBack(setSpringTarget) 118 | } 119 | })) 120 | 121 | const handleSwipeReleased = React.useCallback( 122 | async (setSpringTarget, gesture) => { 123 | // Check if this is a swipe 124 | const dir = getSwipeDirection({ 125 | x: swipeRequirementType === 'velocity' ? gesture.vx : gesture.dx, 126 | y: swipeRequirementType === 'velocity' ? gesture.vy : gesture.dy 127 | }) 128 | 129 | if (dir !== 'none') { 130 | if (flickOnSwipe) { 131 | if (!preventSwipe.includes(dir)) { 132 | if (onSwipe) onSwipe(dir) 133 | 134 | await animateOut(swipeRequirementType === 'velocity' ? ({ 135 | x: gesture.vx, 136 | y: gesture.vy 137 | }) : ( 138 | normalize({ x: gesture.dx, y: gesture.dy }) // Normalize to avoid flicking the card away with super fast speed only direction is wanted here 139 | ), setSpringTarget, swipeRequirementType) 140 | if (onCardLeftScreen) onCardLeftScreen(dir) 141 | return 142 | } 143 | } 144 | } 145 | 146 | // Card was not flicked away, animate back to start 147 | animateBack(setSpringTarget) 148 | }, 149 | [flickOnSwipe, onSwipe, onCardLeftScreen, preventSwipe] 150 | ) 151 | 152 | let swipeThresholdFulfilledDirection = 'none' 153 | const panResponder = React.useMemo( 154 | () => 155 | PanResponder.create({ 156 | // Ask to be the responder: 157 | onStartShouldSetPanResponder: (evt, gestureState) => false, 158 | onStartShouldSetPanResponderCapture: (evt, gestureState) => false, 159 | onMoveShouldSetPanResponder: (evt, gestureState) => { 160 | const { dx, dy } = gestureState 161 | return (dx > 2 || dx < -2 || dy > 2 || dy < -2) 162 | }, 163 | onMoveShouldSetPanResponderCapture: (evt, gestureState) => { 164 | const { dx, dy } = gestureState 165 | return (dx > 2 || dx < -2 || dy > 2 || dy < -2) 166 | }, 167 | 168 | onPanResponderGrant: (evt, gestureState) => { 169 | // The gesture has started. 170 | // Probably wont need this anymore as postion i relative to swipe! 171 | setSpringTarget.current[0].start({ x: gestureState.dx, y: gestureState.dy, rot: 0, config: physics.touchResponsive }) 172 | }, 173 | onPanResponderMove: (evt, gestureState) => { 174 | // Check fulfillment 175 | if (onSwipeRequirementFulfilled || onSwipeRequirementUnfulfilled) { 176 | const dir = getSwipeDirection({ 177 | x: swipeRequirementType === 'velocity' ? gestureState.vx : gestureState.dx, 178 | y: swipeRequirementType === 'velocity' ? gestureState.vy : gestureState.dy 179 | }) 180 | if (dir !== swipeThresholdFulfilledDirection) { 181 | swipeThresholdFulfilledDirection = dir 182 | if (swipeThresholdFulfilledDirection === 'none') { 183 | if (onSwipeRequirementUnfulfilled) onSwipeRequirementUnfulfilled() 184 | } else { 185 | if (onSwipeRequirementFulfilled) onSwipeRequirementFulfilled(dir) 186 | } 187 | } 188 | } 189 | 190 | // use guestureState.vx / guestureState.vy for velocity calculations 191 | // translate element 192 | let rot = ((300 * gestureState.vx) / width) * 15// Magic number 300 different on different devices? Run on physical device! 193 | rot = Math.max(Math.min(rot, settings.maxTilt), -settings.maxTilt) 194 | setSpringTarget.current[0].start({ x: gestureState.dx, y: gestureState.dy, rot, config: physics.touchResponsive }) 195 | }, 196 | onPanResponderTerminationRequest: (evt, gestureState) => { 197 | return true 198 | }, 199 | onPanResponderRelease: (evt, gestureState) => { 200 | // The user has released all touches while this view is the 201 | // responder. This typically means a gesture has succeeded 202 | // enable 203 | handleSwipeReleased(setSpringTarget, gestureState) 204 | } 205 | }), 206 | [] 207 | ) 208 | 209 | return ( 210 | `${rot}deg`) } 217 | ] 218 | }} 219 | className={className} 220 | > 221 | {children} 222 | 223 | ) 224 | } 225 | ) 226 | 227 | module.exports = TinderCard 228 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-tinder-card", 3 | "version": "1.6.4", 4 | "description": "A npm react module for making react elements swipeable like in the dating app tinder.", 5 | "repository": "3DJakob/react-tinder-card", 6 | "license": "MIT", 7 | "files": [ 8 | "index.d.ts", 9 | "index.js", 10 | "useWindowSize.js", 11 | "index.native.js" 12 | ], 13 | "scripts": { 14 | "test": "standard && ts-readme-generator --check" 15 | }, 16 | "dependencies": { 17 | "p-sleep": "^1.1.0" 18 | }, 19 | "devDependencies": { 20 | "@types/react": "^16.9.51", 21 | "standard": "^14.3.1", 22 | "ts-readme-generator": "^0.7.2" 23 | }, 24 | "peerDependencies": { 25 | "@react-spring/native": "^9.5.5", 26 | "@react-spring/web": "^9.5.5", 27 | "react": "^16.8.0 || ^17.0.0 || ^18.0.0" 28 | }, 29 | "peerDependenciesMeta": { 30 | "@react-spring/native": { 31 | "optional": true 32 | }, 33 | "@react-spring/web": { 34 | "optional": true 35 | } 36 | }, 37 | "keywords": [ 38 | "tinder", 39 | "card", 40 | "react-native", 41 | "native", 42 | "ios", 43 | "android", 44 | "web", 45 | "react", 46 | "swipeable", 47 | "swipe", 48 | "physics", 49 | "deck", 50 | "drag", 51 | "draggable" 52 | ] 53 | } 54 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # React Tinder Card 2 | 3 | A react component to make swipeable elements like in the app tinder. 4 | 5 | ## Compatibility 6 | - React 7 | - React Native 8 | 9 | The installation, import and api is identical for both Web and Native. 10 | 11 | ## Demo 12 | ![](demo.gif) 13 | 14 | Try out the interactive demo here. 15 | 16 | Check out the Web demo repo here. 17 | 18 | Check out the Native demo repo here. 19 | 20 | ## Contributing 21 | Want to contribute? Check out the [contributing.md](https://github.com/3DJakob/react-tinder-card/blob/master/CONTRIBUTING.md). 22 | 23 | ## Installation 24 | 25 | ```sh 26 | npm install --save react-tinder-card 27 | ``` 28 | 29 | ### React 30 | If you are using React you will also need spring/web 31 | ```sh 32 | npm install --save @react-spring/web@9.5.5 33 | ``` 34 | 35 | ### React Native 36 | If you are using React Native you will also need spring/native 37 | ```sh 38 | npm install --save @react-spring/native@9.5.5 39 | ``` 40 | 41 | ## Usage 42 | 43 | Import TinderCard and use the component like the snippet. Note that the component will not remove itself after swipe. If you want that behaviour implement that on the `onCardLeftScreen` callback. It is recommended to have `overflow: hidden` on your `#root` to prevent cards from being visible after they go of screen. 44 | 45 | ```js 46 | import TinderCard from 'react-tinder-card' 47 | 48 | // ... 49 | 50 | const onSwipe = (direction) => { 51 | console.log('You swiped: ' + direction) 52 | } 53 | 54 | const onCardLeftScreen = (myIdentifier) => { 55 | console.log(myIdentifier + ' left the screen') 56 | } 57 | 58 | return ( 59 | onCardLeftScreen('fooBar')} preventSwipe={['right', 'left']}>Hello, World! 60 | ) 61 | ``` 62 | 63 | If you want more usage help check out the demo repository code: [Web](https://github.com/3DJakob/react-tinder-card-demo/tree/master/src/examples) / [Native](https://github.com/3DJakob/react-native-tinder-card-demo/tree/master/src/examples) 64 | 65 | The simple example is the minimum code needed to get you started. 66 | 67 | The advanced example implements a state to dynamically remove swiped elements as well as using buttons to trigger swipes. 68 | 69 | Both Web code examples can be tested on the [demo page.](https://3djakob.github.io/react-tinder-card-demo/) The Native code examples can be cloned and runned using `expo start`. 70 | 71 | ## Buttons inside a TinderCard 72 | 73 | If you want a pressable element inside a TinderCard you will need to add `className="pressable"` for it to work properly on mobile. This is because touchstart events are normally prevent defaulted to avoid scrolling the page when dragging cards around. 74 | 75 | ## Props 76 | 77 | ### `flickOnSwipe` 78 | 79 | - optional 80 | - type: `boolean` 81 | - default: `true` 82 | 83 | Whether or not to let the element be flicked away off-screen after a swipe. 84 | 85 | ### `onSwipe` 86 | 87 | - optional 88 | - type: `SwipeHandler` 89 | 90 | Callback that will be executed when a swipe has been completed. It will be called with a single string denoting which direction the swipe was in: `'left'`, `'right'`, `'up'` or `'down'`. 91 | 92 | ### `onCardLeftScreen` 93 | 94 | - optional 95 | - type: `CardLeftScreenHandler` 96 | 97 | Callback that will be executed when a `TinderCard` has left the screen. It will be called with a single string denoting which direction the swipe was in: `'left'`, `'right'`, `'up'` or `'down'`. 98 | 99 | ### `preventSwipe` 100 | 101 | - optional 102 | - type: `Array` 103 | - default: `[]` 104 | 105 | An array of directions for which to prevent swiping out of screen. Valid arguments are `'left'`, `'right'`, `'up'` and `'down'`. 106 | 107 | ### `swipeRequirementType` 108 | 109 | - optional 110 | - type: `'velocity' | 'position'` 111 | - default: `'velocity'` 112 | 113 | What method to evaluate what direction to throw the card on release. 'velocity' will evaluate direction based on the direction of the swiping movement. 'position' will evaluate direction based on the position the card has on the screen like in the app tinder. 114 | If set to position it is recommended to manually set swipeThreshold based on the screen size as not all devices will accommodate the default distance of 300px and the default native swipeThreshold is 1px which most likely is undesirably low. 115 | 116 | ### `swipeThreshold` 117 | 118 | - optional 119 | - type: `number` 120 | - default: `300` 121 | 122 | The threshold of which to accept swipes. If swipeRequirementType is set to velocity it is the velocity threshold and if set to position it is the position threshold. 123 | On native the default value is 1 as the physics works differently there. 124 | If swipeRequirementType is set to position it is recommended to set this based on the screen width so cards can be swiped on all screen sizes. 125 | 126 | ### `onSwipeRequirementFulfilled` 127 | 128 | - optional 129 | - type: `SwipeRequirementFufillUpdate` 130 | 131 | Callback that will be executed when a `TinderCard` has fulfilled the requirement necessary to be swiped in a direction on release. This in combination with `onSwipeRequirementUnfulfilled` is useful for displaying user feedback on the card. When using this it is recommended to use `swipeRequirementType='position'` as this will fire a lot otherwise. 132 | It will be called with a single string denoting which direction the user is swiping: `'left'`, `'right'`, `'up'` or `'down'`. 133 | 134 | ### `onSwipeRequirementUnfulfilled` 135 | 136 | - optional 137 | - type: `SwipeRequirementUnfufillUpdate` 138 | 139 | Callback that will be executed when a `TinderCard` has unfulfilled the requirement necessary to be swiped in a direction on release. 140 | 141 | ### `className` 142 | 143 | - optional 144 | - type: `string` 145 | 146 | HTML attribute class 147 | 148 | ### `children` 149 | 150 | - optional 151 | - type: `React.ReactNode` 152 | 153 | The children passed in is what will be rendered as the actual Tinder-style card. 154 | 155 | ## API 156 | 157 | ### `swipe([dir])` 158 | 159 | - `dir` (`Direction`, optional) - The direction in which the card should be swiped. One of: `'left'`, `'right'`, `'up'` and `'down'`. 160 | - returns `Promise` 161 | 162 | Programmatically trigger a swipe of the card in one of the valid directions `'left'`, `'right'`, `'up'` and `'down'`. This function, `swipe`, can be called on a reference of the TinderCard instance. Check the [example](https://github.com/3DJakob/react-tinder-card-demo/blob/master/src/examples/Advanced.js) code for more details on how to use this. 163 | 164 | ### `restoreCard()` 165 | 166 | - returns `Promise` 167 | 168 | Restore swiped-card state. Use this function if you want to undo a swiped-card (e.g. you have a back button that shows last swiped card or you have a reset button. The promise is resolved once the card is returned 169 | -------------------------------------------------------------------------------- /useWindowSize.js: -------------------------------------------------------------------------------- 1 | const { useState, useEffect } = require('react') 2 | 3 | // this hook ensures that window size is only updated on the client and not on the server when using Next.js 4 | function useWindowSize () { 5 | const [windowSize, setWindowSize] = useState({ 6 | width: undefined, 7 | height: undefined 8 | }) 9 | 10 | useEffect(() => { 11 | function handleResize () { 12 | setWindowSize({ 13 | width: window.innerWidth, 14 | height: window.innerHeight 15 | }) 16 | } 17 | window.addEventListener('resize', handleResize) 18 | handleResize() 19 | 20 | return () => window.removeEventListener('resize', handleResize) 21 | }, []) 22 | return windowSize 23 | } 24 | 25 | module.exports = useWindowSize 26 | --------------------------------------------------------------------------------