-
-
Save hirbod/1e647c10df5cdf5ceb07c3ca559eaa71 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { BottomSheetModal, BottomSheetModalProps } from '@gorhom/bottom-sheet'; | |
import { useCallback, useRef } from 'react'; | |
import { BackHandler, NativeEventSubscription } from 'react-native'; | |
/** | |
* hook that dismisses the bottom sheet on the hardware back button press if it is visible | |
* @param bottomSheetRef ref to the bottom sheet which is going to be closed/dismissed on the back press | |
*/ | |
export const useBottomSheetBackHandler = ( | |
bottomSheetRef: React.RefObject<BottomSheetModal | null>, | |
) => { | |
const backHandlerSubscriptionRef = useRef<NativeEventSubscription | null>( | |
null, | |
); | |
const handleSheetPositionChange = useCallback< | |
NonNullable<BottomSheetModalProps['onChange']> | |
>( | |
index => { | |
const isBottomSheetVisible = index >= 0; | |
if (isBottomSheetVisible && !backHandlerSubscriptionRef.current) { | |
// setup the back handler if the bottom sheet is right in front of the user | |
backHandlerSubscriptionRef.current = BackHandler.addEventListener( | |
'hardwareBackPress', | |
() => { | |
bottomSheetRef.current?.dismiss(); | |
return true; | |
}, | |
); | |
} else if (!isBottomSheetVisible) { | |
backHandlerSubscriptionRef.current?.remove(); | |
backHandlerSubscriptionRef.current = null; | |
} | |
}, | |
[bottomSheetRef, backHandlerSubscriptionRef], | |
); | |
return { handleSheetPositionChange }; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment