Last active
March 13, 2020 21:59
-
-
Save Sivli-Embir/6885d5f18e30a05a667e1c921cf8d286 to your computer and use it in GitHub Desktop.
RN5 on back hook
This file contains 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 React, {useLayoutEffect} from 'react' | |
import useRN5Back from './useRN5Back' | |
export default function Example({navigation}) { | |
const [headerLeft, onBack] = useRN5Back(navigation, () => { //note any variables here | |
console.log('I am doing cleanup before onBack!') | |
}) | |
useLayoutEffect(() => { | |
navigation.setOptions({headerLeft}); | |
}, [navigation]) //if the hook function has variables they be deps here | |
return null //UI here, such as a button with onPress={onBack} | |
} |
This file contains 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 React, { useCallback } from 'react' | |
import { BackHandler } from 'react-native' | |
import { useFocusEffect } from '@react-navigation/native'; | |
import { HeaderBackButton } from '@react-navigation/stack' | |
export default function useRN5Back(navigation, callback) { | |
useFocusEffect( | |
useCallback(() => { | |
const onBackPress = () => { | |
callback(); | |
return true; | |
}; | |
BackHandler.addEventListener('hardwareBackPress', onBackPress); | |
return () => BackHandler.removeEventListener('hardwareBackPress', onBackPress); | |
}, [callback]) | |
) | |
const customGoBack = () => { | |
callback() | |
navigation.goBack() | |
} | |
const customBackUI = () => { | |
return <HeaderBackButton onPress={customGoBack}/> | |
} | |
return [customBackUI, customGoBack] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment