Front-end Blog

Front-end Blog

React Native Custom Navigation Service (TypeScript)

There are some ways to redirect to a screen in React Native. I will write one of my favorite.

Create navigationService.ts and paste these:

import * as React from 'react';
import {DrawerActions, NavigationContainerRef} from '@react-navigation/native';

export const navigationRef = React.createRef<NavigationContainerRef>();

export const navigate = (name: string, params?: any) => {
  navigationRef.current?.navigate(name, params);
};

export const openDrawer = () => {
  navigationRef.current?.dispatch(DrawerActions.openDrawer());
};

export const goBack = () => {
  navigationRef.current?.goBack();
};

export const redirectToLoginScreen = () => navigate("Login");

Create app like that and pass navigationRef from navigationService

const App = () => {
  return (
    <NavigationContainer ref={navigationRef}>
      <DrawerNavigator />
    </NavigationContainer>
  );
};

Use like this when you want to redirect to login screen:

  useEffect(() => {
    if(!isLogged) {
      redirectToLogin()
    }
  }, [isLogged])

Or you can open drawer menu like this:

<IconButton
  marginLeft={'auto'}
  variant={'ghost'}
  onPress={openDrawer} // <--- here
  colorScheme={'dark'}
  icon={
    <Icon
      size="sm"
      as={<MaterialCommunityIcons name={'menu'} color={'#fff'} />}
      color="white"
    />
  }
/>

Thats all!

 
Share this