How to Pass Params Between Screens in React Native
In React Native, you pass params between screens using
React Navigation by sending params in the navigate function and accessing them via route.params in the target screen. This allows you to share data like strings or objects when moving from one screen to another.Syntax
To pass params, use navigation.navigate('ScreenName', { paramName: value }). In the receiving screen, access params with route.params.paramName.
navigation: The navigation prop to move between screens.
route: The route prop containing params sent.
javascript
navigation.navigate('Details', { userId: 42 }); // In Details screen const userId = route.params.userId;
Example
This example shows two screens: Home and Details. Home sends a userId param to Details, which displays it.
javascript
import React from 'react'; import { Button, Text, View } from 'react-native'; import { NavigationContainer } from '@react-navigation/native'; import { createStackNavigator } from '@react-navigation/stack'; function HomeScreen({ navigation }) { return ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> <Button title="Go to Details" onPress={() => navigation.navigate('Details', { userId: 42 })} /> </View> ); } function DetailsScreen({ route }) { const { userId } = route.params; return ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> <Text>User ID: {userId}</Text> </View> ); } const Stack = createStackNavigator(); export default function App() { return ( <NavigationContainer> <Stack.Navigator> <Stack.Screen name="Home" component={HomeScreen} /> <Stack.Screen name="Details" component={DetailsScreen} /> </Stack.Navigator> </NavigationContainer> ); }
Output
Screen shows a button labeled 'Go to Details'. When tapped, it navigates to Details screen showing text 'User ID: 42'.
Common Pitfalls
- Forgetting to pass params in
navigatecausesroute.paramsto be undefined. - Accessing params without checking if they exist can cause errors.
- Using
navigation.pushinstead ofnavigatecan create multiple screens with same params unintentionally.
Always check if route.params exists before using.
javascript
function DetailsScreen({ route }) { // Wrong: assumes params always exist // const userId = route.params.userId; // Right: check if params exist const userId = route.params ? route.params.userId : 'No ID'; return <Text>User ID: {userId}</Text>; }
Quick Reference
Passing params: navigation.navigate('Screen', { paramName: value })
Accessing params: route.params.paramName
Check params: Use conditional checks to avoid errors if params are missing.
Key Takeaways
Use navigation.navigate with a params object to send data between screens.
Access passed params in the target screen via route.params.
Always check if route.params exists before using to avoid errors.
React Navigation handles screen transitions and param passing smoothly.
Avoid using navigation.push repeatedly with same params to prevent stacking screens.