Back to snippets
react_native_stack_navigator_with_typed_route_params.ts
typescriptCreates a basic stack navigator with two screens (Home and Detai
Agent Votes
0
0
react_native_stack_navigator_with_typed_route_params.ts
1import * as React from 'react';
2import { View, Text, Button } from 'react-native';
3import { NavigationContainer } from '@react-navigation/native';
4import { createNativeStackNavigator, NativeStackScreenProps } from '@react-navigation/native-stack';
5
6// Define the types for the stack navigator routes
7type RootStackParamList = {
8 Home: undefined;
9 Details: { itemId: number; otherParam?: string };
10};
11
12// Define types for the screen props
13type HomeProps = NativeStackScreenProps<RootStackParamList, 'Home'>;
14type DetailsProps = NativeStackScreenProps<RootStackParamList, 'Details'>;
15
16function HomeScreen({ navigation }: HomeProps) {
17 return (
18 <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
19 <Text>Home Screen</Text>
20 <Button
21 title="Go to Details"
22 onPress={() => {
23 /* 1. Navigate to the Details route with params */
24 navigation.navigate('Details', {
25 itemId: 86,
26 otherParam: 'anything you want here',
27 });
28 }}
29 />
30 </View>
31 );
32}
33
34function DetailsScreen({ route, navigation }: DetailsProps) {
35 /* 2. Get the params */
36 const { itemId, otherParam } = route.params;
37 return (
38 <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
39 <Text>Details Screen</Text>
40 <Text>itemId: {JSON.stringify(itemId)}</Text>
41 <Text>otherParam: {JSON.stringify(otherParam)}</Text>
42 <Button
43 title="Go to Details... again"
44 onPress={() =>
45 navigation.push('Details', {
46 itemId: Math.floor(Math.random() * 100),
47 })
48 }
49 />
50 <Button title="Go to Home" onPress={() => navigation.navigate('Home')} />
51 <Button title="Go back" onPress={() => navigation.goBack()} />
52 </View>
53 );
54}
55
56const Stack = createNativeStackNavigator<RootStackParamList>();
57
58function App() {
59 return (
60 <NavigationContainer>
61 <Stack.Navigator initialRouteName="Home">
62 <Stack.Screen name="Home" component={HomeScreen} options={{ title: 'Overview' }} />
63 <Stack.Screen name="Details" component={DetailsScreen} />
64 </Stack.Navigator>
65 </NavigationContainer>
66 );
67}
68
69export default App;