Menu

How To Use Router In React Native

Hello guys,
We all know that mobile applications are beneficial in today's time. Due to its high demand, many developers are moving from Web to mobile apps. Today we will learn how we can use routing in the mobile app. 
In React Native, you can use the React Navigation library to implement routing and navigation between different screens in your application. Here are the basic steps to use the React Navigation library to set up routing in your React Native application:
Let's Start.

1. Install the React Navigation library by running the following command in your terminal:

npm install @react-navigation/native

This command will install the react-navigation package in your application. Which will use to create navigation to the screens.

  1. Install the dependencies required by the library by running the following command:
npm install react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view

This command will extra related packages to react-navigation.  

  1. Import the required components from the React Navigation library at the top of your file:
import { createStackNavigator } from '@react-navigation/stack';
import { NavigationContainer } from '@react-navigation/native';

Now, we need to import the package to our main page. Which will use to wrap the screen.  

  1. Create a stack navigator by calling the createStackNavigator function and passing in the screens you want to include:
const Stack = createStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen name="Details" component={DetailsScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

In this example, we have created a Stack.Navigator component and passed in two screens: HomeScreen and DetailsScreen. When the user navigates to the DetailsScreen, the DetailsScreen the component will be rendered

 

  1. In each of your screen components, you can use the navigation prop to navigate to other screens:
function HomeScreen({ navigation }) {
  return (
    <View>
      <Text>Home Screen</Text>
      <Button
        title="Go to Details"
        onPress={() => navigation.navigate('Details')}
      />
    </View>
  );
}

In this example, we have created a button that, when pressed, will navigate to the DetailsScreen by calling the navigation.navigate function and passing in the name of the screen we want to navigate to.

That's the basic setup for using the React Navigation library to implement routing in your React Native application. You can find more information on how to customize your navigation in the official documentation: https://reactnavigation.org/docs/getting-started.

I hope this example is helpful to you.

Thanks

1034
Search

Ads