Last active
March 10, 2021 18:02
-
-
Save surajsly/92cb9643a11f99c6c940755e90f45ef4 to your computer and use it in GitHub Desktop.
some react native snippets to be used in future
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
// change default back behavior for screens | |
React.useEffect(() => { | |
const backAction = () => { | |
Alert.alert("Hold on!", "Are you sure you want to go back?", [ | |
{ | |
text: "Cancel", | |
onPress: () => null, | |
style: "cancel", | |
}, | |
{ text: "YES", onPress: () => BackHandler.exitApp() }, | |
]); | |
return true; | |
}; | |
const backHandler = BackHandler.addEventListener( | |
"hardwareBackPress", | |
backAction | |
); | |
return () => backHandler.remove(); | |
}, []); | |
// change back behavior for one particular scree | |
const navigation = useNavigation(); | |
const hasUnsavedChanges = true; | |
React.useEffect( | |
() => | |
navigation.addListener("beforeRemove", (e) => { | |
if (!hasUnsavedChanges) { | |
// If we don't have unsaved changes, then we don't need to do anything | |
return; | |
} | |
// Prevent default behavior of leaving the screen | |
e.preventDefault(); | |
// Prompt the user before leaving the screen | |
Alert.alert( | |
"Discard changes?", | |
"You have unsaved changes. Are you sure to discard them and leave the screen?", | |
[ | |
{ text: "Don't leave", style: "cancel", onPress: () => {} }, | |
{ | |
text: "Discard", | |
style: "destructive", | |
// If the user confirmed, then we dispatch the action we blocked earlier | |
// This will continue the action that had triggered the removal of the screen | |
onPress: () => BackHandler.exitApp(), | |
}, | |
] | |
); | |
}), | |
[navigation, hasUnsavedChanges] | |
); | |
// How to remove header from react native tab | |
// SET options={{ headerShown: false }} IN <TabOneStack.Screen> | |
// EXAMPLE | |
<TabOneStack.Navigator> | |
<TabOneStack.Screen | |
name="TabOneScreen" | |
component={TabOneScreen} | |
options={{ headerShown: false }} | |
/> | |
</TabOneStack.Navigator> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment