React Navigation provides a hook that helps you access the route object. It is the useRoute hook. This article will walk you through a complete example of using this hook in a React Native mobile app.
Note: To use hooks, we have to use functional components, not class-based components.
Table of Contents
Example
The simple app we are going to build consists of 2 screens: HomeScreen and ProductScreen. The main content of each screen is just some text that presents the route name and the route key (this information is retrieved by using the useRoute hook).
App Preview
Here’s how it works:
The Code
Create a new React Native project, delete all the default code in App.js, and add this (don’t forget to install the required packages for React Navigation 6 – the latest version):
import React from "react";
import { View, Text, StyleSheet, Button } from "react-native";
import { NavigationContainer, useRoute } from "@react-navigation/native";
import { createNativeStackNavigator } from "@react-navigation/native-stack";
const MainStack = createNativeStackNavigator();
// This component displays the information about the current route
// It will be used in both HomeScreen and ProductScreen
const RouteInfo = (props) => {
const route = useRoute();
return (
<View>
<Text>Route Name: {route.name}</Text>
<Text>Route Key: {route.key}</Text>
</View>
);
};
// Implement Home Screen
const HomeScreen = (props) => {
return (
<View style={styles.screen}>
<RouteInfo />
<Button
onPress={() => props.navigation.navigate("Product")}
title="Go To Product Screen"
/>
</View>
);
};
// Product Screen
const ProductScreen = (props) => {
return (
<View style={styles.screen}>
<RouteInfo />
</View>
);
};
// Wire everything up in the App component
function App() {
return (
<NavigationContainer>
<MainStack.Navigator>
<MainStack.Screen name="Home" component={HomeScreen} />
<MainStack.Screen name="Product" component={ProductScreen} />
</MainStack.Navigator>
</NavigationContainer>
);
}
export default App;
/// Just some styles
const styles = StyleSheet.create({
screen: {
flex: 1,
justifyContent: "center",
alignItems: "center",
},
});
Afterword
You’ve examined a basic but meaningful example about the useRoute hook of React Navigation. If you’d like to explore more new and interesting things about modern React Native and React, take a look at the following articles:
- Using Switch component in React Native (with Hooks)
- How to Get the Window Width & Height in React Native
- React Native: Make a Button with a Loading Indicator inside
- How to render HTML content in React Native
- React Router Dom: Implement a Not Found (404) Route
You can also check our React topic page and React Native topic page for the latest tutorials and examples.