Skip to content

Instantly share code, notes, and snippets.

@Sivli-Embir

Sivli-Embir/usage.js

Last active Mar 13, 2020
Embed
What would you like to do?
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