@react-navigation/native#StackActions TypeScript Examples

The following examples show how to use @react-navigation/native#StackActions. 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: StackView.tsx    From nlw2-proffy with MIT License 6 votes vote down vote up
private handleCloseRoute = ({ route }: { route: Route<string> }) => {
    const { state, navigation } = this.props;

    if (state.routes.some((r) => r.key === route.key)) {
      // If a route exists in state, trigger a pop
      // This will happen in when the route was closed from the card component
      // e.g. When the close animation triggered from a gesture ends
      navigation.dispatch({
        ...StackActions.pop(),
        source: route.key,
        target: state.key,
      });
    } else {
      // We need to clean up any state tracking the route and pop it immediately
      this.setState((state) => ({
        routes: state.routes.filter((r) => r.key !== route.key),
        openingRouteKeys: state.openingRouteKeys.filter(
          (key) => key !== route.key
        ),
        closingRouteKeys: state.closingRouteKeys.filter(
          (key) => key !== route.key
        ),
      }));
    }
  };
Example #2
Source File: Modal.tsx    From jellyfin-audio-player with MIT License 6 votes vote down vote up
Modal: React.FC<Props> = ({ children, fullSize = true }) => {
    const defaultStyles = useDefaultStyles();
    const navigation = useNavigation();
    const closeModal = useCallback(() => {
        navigation.dispatch(StackActions.popToTop());    
    }, [navigation]);

    return (
        <Background style={defaultStyles.modal}>
            {!fullSize && <Spacer onPress={closeModal} />}
            <Container style={defaultStyles.modalInner} fullSize={fullSize}>
                {children}
            </Container>
            {!fullSize && <Spacer onPress={closeModal} />}
        </Background>
    );
}
Example #3
Source File: HeaderBackIcon.tsx    From orangehrm-os-mobile with GNU General Public License v3.0 6 votes vote down vote up
HeaderBackIcon = (props: HeaderBackIconProps) => {
  const {theme} = props;
  return (
    <IconButton
      buttonProps={{
        onPress: () => {
          props.navigation.dispatch(StackActions.pop());
        },
      }}
      iconProps={{
        name: Platform.OS === 'ios' ? 'chevron-thin-left' : 'arrow-back',
        type: Platform.OS === 'ios' ? 'Entypo' : 'MaterialIcons',
        style: {
          fontSize: theme.typography.headerIconSize,
          color: theme.typography.secondaryColor,
        },
      }}
    />
  );
}
Example #4
Source File: SelectInstance.tsx    From orangehrm-os-mobile with GNU General Public License v3.0 6 votes vote down vote up
componentDidUpdate(prevProps: SelectInstanceProps) {
    if (this.props.instanceUrl !== prevProps.instanceUrl) {
      this.setCurrentInstanceUrl();
    }
    if (
      this.props.checkingInstance === false &&
      this.props.instanceExists === true
    ) {
      this.props.navigation.dispatch(StackActions.replace(LOGIN));
    }
  }
Example #5
Source File: navigationService.ts    From react-native-template with MIT License 6 votes vote down vote up
replace = <T extends object>(name: Screens, params?: T) => {
  if (isMountedRef.current && navigationRef.current) {
    navigationRef.current.dispatch(
      StackActions.replace(name, params)
    )
  } else {
    throw new Error(ERROR_NOT_INIT)
  }
}
Example #6
Source File: navigationService.ts    From react-native-template with MIT License 6 votes vote down vote up
pop = (count: number) => {
  if (isMountedRef.current && navigationRef.current) {
    navigationRef.current.dispatch(
      StackActions.pop(count)
    )
  } else {
    throw new Error(ERROR_NOT_INIT)
  }
}
Example #7
Source File: createStackNavigator.tsx    From nlw2-proffy with MIT License 5 votes vote down vote up
function StackNavigator({
  initialRouteName,
  children,
  screenOptions,
  ...rest
}: Props) {
  const defaultOptions = {
    gestureEnabled: Platform.OS === 'ios',
    animationEnabled:
      Platform.OS !== 'web' &&
      Platform.OS !== 'windows' &&
      Platform.OS !== 'macos',
  };

  const { state, descriptors, navigation } = useNavigationBuilder<
    StackNavigationState,
    StackRouterOptions,
    StackNavigationOptions,
    StackNavigationEventMap
  >(StackRouter, {
    initialRouteName,
    children,
    screenOptions:
      typeof screenOptions === 'function'
        ? (...args) => ({
            ...defaultOptions,
            ...screenOptions(...args),
          })
        : {
            ...defaultOptions,
            ...screenOptions,
          },
  });

  React.useEffect(
    () =>
      navigation.addListener &&
      navigation.addListener('tabPress', (e) => {
        const isFocused = navigation.isFocused();

        // Run the operation in the next frame so we're sure all listeners have been run
        // This is necessary to know if preventDefault() has been called
        requestAnimationFrame(() => {
          if (
            state.index > 0 &&
            isFocused &&
            !(e as EventArg<'tabPress', true>).defaultPrevented
          ) {
            // When user taps on already focused tab and we're inside the tab,
            // reset the stack to replicate native behaviour
            navigation.dispatch({
              ...StackActions.popToTop(),
              target: state.key,
            });
          }
        });
      }),
    [navigation, state.index, state.key]
  );

  return (
    <StackView
      {...rest}
      state={state}
      descriptors={descriptors}
      navigation={navigation}
    />
  );
}
Example #8
Source File: index.tsx    From jellyfin-audio-player with MIT License 5 votes vote down vote up
export default function SetJellyfinServer() {
    const defaultStyles = useDefaultStyles();
    // State for first screen
    const [serverUrl, setServerUrl] = useState<string>();
    const [isLogginIn, setIsLogginIn] = useState<boolean>(false);

    // Handlers needed for dispatching stuff
    const dispatch = useAppDispatch();
    const navigation = useNavigation();

    // Save creedentials to store and close the modal
    const saveCredentials = useCallback((credentials) => {
        dispatch(setJellyfinCredentials(credentials));
        navigation.dispatch(StackActions.popToTop());    
    }, [navigation, dispatch]);

    return (
        <Modal>
            {isLogginIn ? (
                <CredentialGenerator 
                    serverUrl={serverUrl as string}
                    onCredentialsRetrieved={saveCredentials}
                />
            ) : (
                <View style={{ padding: 20, flex: 1, justifyContent: 'center', alignItems: 'center' }}>
                    <Text>
                        {t('set-jellyfin-server-instruction')}
                    </Text>
                    <Input
                        placeholder="https://jellyfin.yourserver.io/"
                        onChangeText={setServerUrl}
                        value={serverUrl} 
                        keyboardType="url"
                        autoCapitalize="none"
                        autoCorrect={false}
                        style={[ defaultStyles.input, { width: '100%' } ]}
                    />
                    <Button
                        title={t('set-jellyfin-server')}
                        onPress={() => setIsLogginIn(true)}
                        disabled={!serverUrl?.length} 
                        color={THEME_COLOR}
                    />
                </View>
            )}
        </Modal>
    );
}
Example #9
Source File: TrackPopupMenu.tsx    From jellyfin-audio-player with MIT License 5 votes vote down vote up
function TrackPopupMenu() {
    // Retrieve trackId from route
    const { params: { trackId } } = useRoute<Route>();

    // Retrieve helpers
    const navigation = useNavigation();
    const dispatch = useAppDispatch();
    const playTracks = usePlayTracks();
    const getImage = useGetImage();

    // Retrieve data from store
    const track = useTypedSelector((state) => state.music.tracks.entities[trackId]);
    const isDownloaded = useTypedSelector(selectIsDownloaded(trackId));

    // Set callback to close the modal
    const closeModal = useCallback(() => {
        navigation.dispatch(StackActions.popToTop());    
    }, [navigation]);

    // Callback for adding the track to the queue as the next song
    const handlePlayNext = useCallback(() => {
        playTracks([trackId], { method: 'add-after-currently-playing', play: false });
        closeModal();
    }, [playTracks, closeModal, trackId]);

    // Callback for adding the track to the end of the queue
    const handleAddToQueue = useCallback(() => {
        playTracks([trackId], { method: 'add-to-end', play: false });
        closeModal();
    }, [playTracks, closeModal, trackId]);

    // Callback for downloading the track
    const handleDownload = useCallback(() => {
        dispatch(queueTrackForDownload(trackId));
        closeModal();
    }, [trackId, dispatch, closeModal]);

    // Callback for removing the downloaded track
    const handleDelete = useCallback(() => {
        dispatch(removeDownloadedTrack(trackId));
        closeModal();
    }, [trackId, dispatch, closeModal]);

    return (
        <Container>
            <Artwork src={getImage(track?.Id || '')} />
            <Header>{track?.Name}</Header>
            <SubHeader style={{ marginBottom: 18 }}>{track?.AlbumArtist} {track?.Album ? '— ' + track?.Album : ''}</SubHeader>
            <WrappableButtonRow>
                <WrappableButton title={t('play-next')} icon={PlayIcon} onPress={handlePlayNext} />
                <WrappableButton title={t('add-to-queue')} icon={QueueAppendIcon} onPress={handleAddToQueue} />
                {isDownloaded ? (
                    <WrappableButton title={t('delete-track')} icon={TrashIcon} onPress={handleDelete} />
                ) : (
                    <WrappableButton title={t('download-track')} icon={DownloadIcon} onPress={handleDownload} />
                )}
            </WrappableButtonRow>
        </Container>
    );
}
Example #10
Source File: LeaveRequestSuccess.tsx    From orangehrm-os-mobile with GNU General Public License v3.0 5 votes vote down vote up
onPressHome = () => {
    const {initialRoute, navigation} = this.props;
    navigation.dispatch(StackActions.pop());
    navigation.dispatch(DrawerActions.jumpTo(initialRoute));
  };
Example #11
Source File: LeaveRequestSuccess.tsx    From orangehrm-os-mobile with GNU General Public License v3.0 5 votes vote down vote up
onRequestClose = () => {
    const {navigation} = this.props;
    navigation.dispatch(StackActions.pop());
  };
Example #12
Source File: Login.tsx    From orangehrm-os-mobile with GNU General Public License v3.0 5 votes vote down vote up
handleSelectInstanceOnClick = () => {
    const {navigation, resetInstanceCheckState} = this.props;
    resetInstanceCheckState();
    navigation.dispatch(StackActions.replace(SELECT_INSTANCE));
  };
Example #13
Source File: SelectInstance.tsx    From orangehrm-os-mobile with GNU General Public License v3.0 5 votes vote down vote up
onPressGetHelp = () => {
    this.props.navigation.dispatch(StackActions.push(SELECT_INSTANCE_HELP));
  };
Example #14
Source File: SelectInstanceHelp.tsx    From orangehrm-os-mobile with GNU General Public License v3.0 5 votes vote down vote up
onPressClose = () => {
    this.props.navigation.dispatch(StackActions.pop());
  };
Example #15
Source File: PunchRequestSuccess.tsx    From orangehrm-os-mobile with GNU General Public License v3.0 5 votes vote down vote up
onClickHomeButton = () => {
    const {initialRoute, navigation} = this.props;
    navigation.dispatch(StackActions.pop());
    navigation.dispatch(DrawerActions.jumpTo(initialRoute));
  };