@react-navigation/native#NavigationContainerRef TypeScript Examples

The following examples show how to use @react-navigation/native#NavigationContainerRef. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DevPersistedNavigationContainer.tsx    From mobile with Apache License 2.0 5 votes vote down vote up
function DevPersistedNavigationContainerImpl(
  {persistKey, onStateChange, ...others}: DevPersistedNavigationContainerProps,
  forwardedRef: React.Ref<NavigationContainerRef>,
) {
  const [isReady, setIsReady] = React.useState(false);
  const [initialState, setInitialState] = React.useState<InitialState | undefined>();
  const persistInteractionRef = React.useRef<{cancel: () => void} | null>(null);
  const onStateChangeInternal = React.useCallback(
    state => {
      const persistState = async () => {
        persistInteractionRef.current = null;
        try {
          await AsyncStorage.setItem(persistKey, JSON.stringify(state));
        } catch (ex) {
          console.warn(`Failed to persist state. ${ex.message}`);
        }
      };

      if (persistInteractionRef.current !== null) {
        persistInteractionRef.current.cancel();
      }

      if (state != null) {
        persistInteractionRef.current = InteractionManager.runAfterInteractions(persistState);
      }

      if (onStateChange != null) {
        onStateChange(state);
      }
    },
    [onStateChange, persistKey],
  );

  React.useEffect(() => {
    const loadPersistedState = async () => {
      try {
        const jsonString = await AsyncStorage.getItem(persistKey);
        if (jsonString != null) {
          setInitialState(JSON.parse(jsonString));
        }
        setIsReady(true);
      } catch (ex) {
        console.warn(`Failed to load state. ${ex.message}`);
        setIsReady(true);
      }
    };
    loadPersistedState();
  }, [persistKey]);

  if (!isReady) {
    return null;
  }

  return (
    <NavigationContainer
      {...others}
      key={persistKey}
      ref={forwardedRef}
      initialState={initialState}
      onStateChange={onStateChangeInternal}
    />
  );
}
Example #2
Source File: navigation.tsx    From protect-scotland with Apache License 2.0 5 votes vote down vote up
Navigation: FC<Navigation> = ({
  notification,
  exposureNotificationClicked,
  completedExposureOnboarding,
  setState
}) => {
  const {t} = useTranslation();
  const {accessibility} = useApplication();
  const {getTranslation} = useAgeGroupTranslation();
  const app = useApplication();

  useEffect(() => {
    (isMountedRef as MutableRefObject<boolean>).current = true;
    return () => {
      (isMountedRef as MutableRefObject<boolean>).current = false;
    };
  }, []);

  useEffect(() => {
    if (Platform.OS !== 'ios') {
      return;
    }

    if (navigationRef.current && notification) {
      navigationRef.current.navigate(ScreenNames.closeContact);

      setState((s) => ({...s, notification: null}));
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [notification]);

  useEffect(() => {
    if (Platform.OS !== 'android') {
      return;
    }

    if (navigationRef.current && exposureNotificationClicked) {
      navigationRef.current.navigate(ScreenNames.closeContact);
      setState((s) => ({...s, exposureNotificationClicked: null}));
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [exposureNotificationClicked]);

  const initialScreen =
    app.user && completedExposureOnboarding
      ? ScreenNames.dashboard
      : ScreenNames.ageConfirmation;

  return (
    <NavigationContainer
      ref={(e) => {
        notificationHooks.navigation = e as NavigationContainerRef;
        (navigationRef as MutableRefObject<NavigationContainerRef | null>).current = e;
      }}>
      <Stack.Navigator
        screenOptions={{
          cardStyleInterpolator: CardStyleInterpolators.forHorizontalIOS,
          cardStyle: {backgroundColor: 'transparent'},
          gestureEnabled: true,
          gestureDirection: 'horizontal',
          animationEnabled: !accessibility.reduceMotionEnabled
        }}
        initialRouteName={initialScreen}
        headerMode="float"
        mode="modal">
        {Screens(t, getTranslation).map((screen, index) => (
          // @ts-ignore
          <Stack.Screen {...screen} key={`screen-${index}`} />
        ))}
      </Stack.Navigator>
    </NavigationContainer>
  );
}
Example #3
Source File: navigation.tsx    From protect-scotland with Apache License 2.0 5 votes vote down vote up
navigationRef = React.createRef<NavigationContainerRef>()
Example #4
Source File: Routes.tsx    From vsinder with Apache License 2.0 5 votes vote down vote up
Routes: React.FC<RoutesProps> = ({}) => {
  const { editorBackground } = useTheme();
  const { data, isLoading } = useQuery<MeResponse>("/me");
  const routeNameRef = React.useRef<string | undefined>();
  const navigationRef = React.useRef<NavigationContainerRef>(null);

  let body: any = null;

  if (isLoading) {
    body = <FullscreenLoading />;
  } else if (!data?.user) {
    body = <AuthStack />;
  } else if (data.user.goal && data.user.codeImgIds.length) {
    body = <MainTabStack />;
  } else {
    body = <ProfileStack isNewUser />;
  }

  return (
    <SafeAreaView style={{ flex: 1, backgroundColor: editorBackground }}>
      <ReactQueryErrorResetBoundary>
        {({ reset }) => (
          <ErrorBoundary
            onReset={reset}
            FallbackComponent={ErrorFallback}
            onError={myErrorHandler}
          >
            <NavigationContainer
              ref={navigationRef}
              onStateChange={() => {
                const previousRouteName = routeNameRef.current;
                const currentRouteName = navigationRef.current?.getCurrentRoute()
                  ?.name;

                if (previousRouteName !== currentRouteName) {
                  if (
                    !["swiper", "viewProfile", "matchy"].includes(
                      currentRouteName || ""
                    )
                  ) {
                    useShowTabs.getState().set({ show: false });
                  } else {
                    useShowTabs.getState().set({ show: true });
                  }
                }

                routeNameRef.current = currentRouteName;
              }}
              linking={linking}
              fallback={<FullscreenLoading />}
            >
              {body}
            </NavigationContainer>
          </ErrorBoundary>
        )}
      </ReactQueryErrorResetBoundary>
    </SafeAreaView>
  );
}
Example #5
Source File: Routes.tsx    From vsinder-app with Apache License 2.0 5 votes vote down vote up
Routes: React.FC<RoutesProps> = ({}) => {
  const { editorBackground } = useTheme();
  const { data, isLoading } = useQuery<MeResponse>("/me");
  const routeNameRef = React.useRef<string | undefined>();
  const navigationRef = React.useRef<NavigationContainerRef>(null);

  let body: any = null;

  if (isLoading) {
    body = <FullscreenLoading />;
  } else if (!data?.user) {
    body = <AuthStack />;
  } else if (data.user.goal && data.user.codeImgIds.length) {
    body = <MainTabStack />;
  } else {
    body = <ProfileStack isNewUser />;
  }

  return (
    <SafeAreaView style={{ flex: 1, backgroundColor: editorBackground }}>
      <ReactQueryErrorResetBoundary>
        {({ reset }) => (
          <ErrorBoundary
            onReset={reset}
            FallbackComponent={ErrorFallback}
            onError={myErrorHandler}
          >
            <NavigationContainer
              ref={navigationRef}
              onStateChange={() => {
                const previousRouteName = routeNameRef.current;
                const currentRouteName = navigationRef.current?.getCurrentRoute()
                  ?.name;

                if (previousRouteName !== currentRouteName) {
                  if (
                    !["swiper", "viewProfile", "matchy"].includes(
                      currentRouteName || ""
                    )
                  ) {
                    useShowTabs.getState().set({ show: false });
                  } else {
                    useShowTabs.getState().set({ show: true });
                  }
                }

                routeNameRef.current = currentRouteName;
              }}
              linking={linking}
              fallback={<FullscreenLoading />}
            >
              {body}
            </NavigationContainer>
          </ErrorBoundary>
        )}
      </ReactQueryErrorResetBoundary>
    </SafeAreaView>
  );
}
Example #6
Source File: DevPersistedNavigationContainer.tsx    From mobile with Apache License 2.0 5 votes vote down vote up
function DevPersistedNavigationContainerImpl(
  {persistKey, onStateChange, ...others}: DevPersistedNavigationContainerProps,
  forwardedRef: React.Ref<NavigationContainerRef>,
) {
  const [isReady, setIsReady] = React.useState(false);
  const [initialState, setInitialState] = React.useState<InitialState | undefined>();
  const persistInteractionRef = React.useRef<{cancel: () => void} | null>(null);
  const onStateChangeInternal = React.useCallback(
    state => {
      const persistState = async () => {
        persistInteractionRef.current = null;
        try {
          await AsyncStorage.setItem(persistKey, JSON.stringify(state));
        } catch (error) {
          captureException(`Failed to persist state.`, error);
        }
      };

      if (persistInteractionRef.current !== null) {
        persistInteractionRef.current.cancel();
      }

      if (state != null) {
        persistInteractionRef.current = InteractionManager.runAfterInteractions(persistState);
      }

      if (onStateChange != null) {
        onStateChange(state);
      }
    },
    [onStateChange, persistKey],
  );

  React.useEffect(() => {
    const loadPersistedState = async () => {
      try {
        const jsonString = await AsyncStorage.getItem(persistKey);
        if (jsonString != null) {
          setInitialState(JSON.parse(jsonString));
        }
        setIsReady(true);
      } catch (error) {
        captureException(`Failed to load state.`, error);
        setIsReady(true);
      }
    };
    loadPersistedState();
  }, [persistKey]);

  if (!isReady) {
    return null;
  }

  return (
    <NavigationContainer
      {...others}
      key={persistKey}
      ref={forwardedRef}
      initialState={initialState}
      onStateChange={onStateChangeInternal}
    />
  );
}
Example #7
Source File: navigation.ts    From hive-keychain-mobile with MIT License 5 votes vote down vote up
navigator: NavigationContainerRef | null
Example #8
Source File: navigation.ts    From hive-keychain-mobile with MIT License 5 votes vote down vote up
setNavigator = (nav: NavigationContainerRef | null) => {
  navigator = nav;
}
Example #9
Source File: navigation.ts    From orangehrm-os-mobile with GNU General Public License v3.0 5 votes vote down vote up
navigationRef = React.createRef<NavigationContainerRef>()
Example #10
Source File: App.tsx    From hive-keychain-mobile with MIT License 4 votes vote down vote up
App = ({hasAccounts, auth, rpc}: PropsFromRedux) => {
  let routeNameRef: React.MutableRefObject<string> = useRef();
  let navigationRef: React.MutableRefObject<NavigationContainerRef> = useRef();

  useEffect(() => {
    setupLinking();
    return () => {
      clearLinkingListeners();
    };
  }, []);
  //TODO:Delete
  // useEffect(() => {
  //   console.log(JSON.stringify(has));
  // }, [has]);

  useEffect(() => {
    RNBootSplash.hide({fade: true});
  }, []);

  useEffect(() => {
    Orientation.lockToPortrait();
  }, []);

  useEffect(() => {
    setRpc(rpc as Rpc);
  }, [rpc]);

  // useEffect(() => {
  //   if (!!auth.mk && has) {
  //     showHASInitRequest(has);
  //   }
  // }, [auth.mk, has]);

  const renderNavigator = () => {
    if (!hasAccounts) {
      // No accounts, sign up process
      return <SignUpStack />;
    } else if (!auth.mk) {
      // has account but not authenticated yet -> Unlock
      return <UnlockStack />;
    } else {
      return <MainDrawer />;
    }
  };

  const renderRootNavigator = () => {
    return (
      <Root.Navigator>
        <Root.Screen
          name="Main"
          component={renderNavigator}
          options={noHeader}
        />
        <Root.Screen name="ModalScreen" component={Modal} {...modalOptions} />
      </Root.Navigator>
    );
  };

  return (
    <NavigationContainer
      ref={(navigator) => {
        setNavigator(navigator);
        navigationRef.current = navigator;
      }}
      onReady={() => {
        const currentRouteName = navigationRef.current.getCurrentRoute().name;
        logScreenView(currentRouteName);
      }}
      onStateChange={async (state) => {
        let currentRouteName = navigationRef.current.getCurrentRoute().name;
        const p = navigationRef.current.getCurrentRoute().params;
        if (currentRouteName === 'WalletScreen') {
          currentRouteName = getToggleElement() || 'WalletScreen';
        }
        if (currentRouteName === 'ModalScreen' && !!p) {
          currentRouteName = 'ModalScreen_' + (p as ModalNavigationRoute).name;
        }
        logScreenView(currentRouteName);
      }}>
      {renderRootNavigator()}
      <Bridge />
    </NavigationContainer>
  );
}