React Navigation 5: useRoute hook example

Last updated on June 6, 2020 A Goodman Loading... Post a comment

React Navigation provides a hook which helps you access to the route object. It is the useRoute hook.

Example

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 5):

import 'react-native-gesture-handler';

import React from 'react';
import {View, Text, StyleSheet, Button} from 'react-native';
import {NavigationContainer, useRoute} from '@react-navigation/native';
import {createStackNavigator} from '@react-navigation/stack';

const MainStack = createStackNavigator();

const RouteInfo = props => {
  const route = useRoute();
  return (
    <View>
      <Text>Route Name: {route.name}</Text>
      <Text>Route Key: {route.key}</Text>
    </View>
  );
};

const HomeScreen = props => {
  return (
    <View style={styles.screen}>
      <RouteInfo />
      <Button
        onPress={() => props.navigation.navigate('Product')}
        title="Go To Product Screen"
      />
    </View>
  );
};

const ProductScreen = props => {
  return (
    <View style={styles.screen}>
      <RouteInfo />
    </View>
  );
};

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',
  },
});

Testing:

See also: How to dynamically set the header title when using React Navigation 5

Related Articles

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x