Skip to content

Instantly share code, notes, and snippets.

@Sivli-Embir
Last active March 13, 2020 21:59
Show Gist options
  • Save Sivli-Embir/6885d5f18e30a05a667e1c921cf8d286 to your computer and use it in GitHub Desktop.
Save Sivli-Embir/6885d5f18e30a05a667e1c921cf8d286 to your computer and use it in GitHub Desktop.
RN5 on back hook
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}
}
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