I have a question about this code, I want to add an Alert if you press the BackButton but only in 2 navigation screen (MARKETPLACE and SHOP) The Alert is to confirm is you want to back or cancel if not How can I do that? My BackButton is the first Stack.Screen This is the code:
<Stack.Navigator>
<Stack.Screen
name='Root'
component={DrawerNavigator}
options={{
headerShown: false,
title: '',
headerBackTitle: 'BackButton
}}/>
<Stack.Screen options={{ title: 'MARKETPLACE' }} name='Marketplace' component={Marketplace} />
<Stack.Screen options={{ title: 'SHOP' }} name='Shop' component={Shopping} />
<Stack.Screen options={{ title: 'CHECKOUT' }} name='Checkout' component={Checkout} />
<Stack.Screen options={{ title: 'CHECK' }} name='Check' component={CheckSuccess} />
</Stack.Navigator>
Starting from @react-navigation/native version 5.7+ you can add beforeRemove listener to the navigation object to prevent going back.
EXAMPLE
function Marketplace({ navigation }) {
const [text, setText] = React.useState('');
const hasUnsavedChanges = Boolean(text);
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: () => navigation.dispatch(e.data.action),
},
]
);
}),
[navigation, hasUnsavedChanges]
);
return (
<TextInput
value={text}
placeholder="Type something…"
onChangeText={setText}
/>
);
}