Skip to content

Commit 927b6f3

Browse files
committed
add useBackHandler for android
1 parent cd2e45b commit 927b6f3

File tree

3 files changed

+31
-0
lines changed

3 files changed

+31
-0
lines changed

README.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ yarn add react-native-hooks
2121
## API
2222
- [useAccessibilityInfo](https://github.com/react-native-community/react-native-hooks#useaccessibilityinfo)
2323
- [useAppState](https://github.com/react-native-community/react-native-hooks#useappstate)
24+
- [useBackHandler](https://github.com/react-native-community/react-native-hooks#usebackhandler)
2425
- [useCameraRoll](https://github.com/react-native-community/react-native-hooks#usecameraroll)
2526
- [useClipboard](https://github.com/react-native-community/react-native-hooks#useclipboard)
2627
- [useDimensions](https://github.com/react-native-community/react-native-hooks#usedimensions)
@@ -47,6 +48,21 @@ import { useAppState } from 'react-native-hooks'
4748
const currentAppState = useAppState()
4849
```
4950

51+
### `useBackHandler`
52+
53+
```js
54+
import { useBackHandler } from 'react-native-hooks'
55+
56+
useBackHandler(() => {
57+
if (shouldBeHandledHere) {
58+
// handle it
59+
return true
60+
}
61+
// let the default thing happen
62+
return false
63+
})
64+
```
65+
5066
### `useCameraRoll`
5167

5268
```js

index.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import useDimensions from './lib/useDimensions'
22
import useAppState from './lib/useAppState'
3+
import useBackHandler from './lib/useBackHandler'
34
import useCameraRoll from './lib/useCameraRoll'
45
import useClipboard from './lib/useClipboard'
56
import useAccessibilityInfo from './lib/useAccessibilityInfo'
@@ -12,6 +13,7 @@ import useDeviceOrientation from './lib/useDeviceOrientation'
1213
export {
1314
useDimensions,
1415
useAppState,
16+
useBackHandler,
1517
useCameraRoll,
1618
useClipboard,
1719
useAccessibilityInfo,

lib/useBackHandler.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import React, { useEffect, useState } from 'react'
2+
import { BackHandler } from 'react-native'
3+
4+
5+
export default (handler) => {
6+
useEffect(() => {
7+
BackHandler.addEventListener('hardwareBackPress', handler)
8+
9+
return () => {
10+
BackHandler.removeEventListener('hardwareBackPress', handler)
11+
}
12+
})
13+
}

0 commit comments

Comments
 (0)