1 | import * as React from 'react';
|
2 | import { BackHandler } from 'react-native';
|
3 | import type { NavigationContainerRef } from '@react-navigation/core';
|
4 |
|
5 | export default function useBackButton(
|
6 | ref: React.RefObject<NavigationContainerRef>
|
7 | ) {
|
8 | React.useEffect(() => {
|
9 | const subscription = BackHandler.addEventListener(
|
10 | 'hardwareBackPress',
|
11 | () => {
|
12 | const navigation = ref.current;
|
13 |
|
14 | if (navigation == null) {
|
15 | return false;
|
16 | }
|
17 |
|
18 | if (navigation.canGoBack()) {
|
19 | navigation.goBack();
|
20 |
|
21 | return true;
|
22 | }
|
23 |
|
24 | return false;
|
25 | }
|
26 | );
|
27 |
|
28 | return () => subscription.remove();
|
29 | }, [ref]);
|
30 | }
|