Last active
September 1, 2020 14:23
-
-
Save evancloutier/a91e9a958b605096c4306062daa5ab69 to your computer and use it in GitHub Desktop.
Using React Navigation navigator outside of components
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
// We can create a `NavigationService` singleton that allow us to access the top-level navigator | |
// for navigation outside of our components. | |
// services/navigation.ts | |
import { NavigationContainerRef } from "@react-navigation/native"; | |
export class NavigationService { | |
public static navigator: NavigationContainerRef; | |
public static setTopLevelNavigator(navigator: NavigationContainerRef) { | |
if (navigator) { | |
this.navigator = navigator; | |
} | |
} | |
} | |
// To use this, we can add a `ref` to our `NavigationContainer` when rendering the root of our app. For example: | |
// navigation/root/index.tsx | |
<NavigationContainer | |
ref={ref => NavigationService.setTopLevelNavigator(ref)} | |
> | |
<Stack.Navigator | |
headerMode="none" | |
screenOptions={{ | |
cardStyle: { backgroundColor: Colors.white }, | |
headerShown: false | |
}} | |
> | |
{authenticated || signup ? ( | |
<Stack.Screen | |
name="Application" | |
component={ApplicationNavigator} | |
initialParams={{ signup }} | |
/> | |
) : ( | |
<Stack.Screen | |
name="Onboarding" | |
component={OnboardingNavigator} | |
options={{ | |
animationTypeForReplace: loading ? "push" : "pop" | |
}} | |
/> | |
)} | |
{isDev && <Stack.Screen name="Storybook" component={Storybook} />} | |
</Stack.Navigator> | |
</NavigationContainer> | |
// Since our root will be rendered when handling push notifications and deep links, | |
// we should be able to access our navigator like so: | |
const handleCommunityNotification = (id: string) => { | |
if (NavigationService.navigator) { | |
const { navigator } = NavigationService; | |
try { | |
navigator.dispatch( | |
TabActions.jumpTo("Community", { | |
screen: "Feed" | |
}) | |
); | |
navigator.dispatch( | |
TabActions.jumpTo("Community", { | |
params: { id, key: id }, | |
screen: "CommunityTask" | |
}) | |
); | |
} catch (error) { | |
NotificationService.displayTextError(); | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment