Handling Navigation in React Native with Expo and React Navigation
Navigation is a crucial part of any mobile application, allowing users to move between different screens seamlessly. In this guide, we will explore how to set up and use React Navigation in a React Native Expo project.
1. Installing React Navigation
Before using React Navigation, you need to install the required dependencies. Open your terminal and run the following commands:
npm install @react-navigation/native
After that, install the required dependencies for React Navigation:
npm install react-native-screens react-native-safe-area-context react-native-gesture-handler react-native-reanimated react-native-vector-icons
Next, install the stack navigator:
npm install @react-navigation/stack
Finally, make sure to add the following to your babel.config.js to enable Reanimated support:
module.exports = {
presets: ['babel-preset-expo'],
plugins: ['react-native-reanimated/plugin'],
};
2. Setting Up Navigation
To start using navigation, wrap your app in a NavigationContainer in App.js:
import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import HomeScreen from './screens/HomeScreen';
import DetailsScreen from './screens/DetailsScreen';
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>
);
}
3. Creating Screens
Let's create two screens: HomeScreen.js and DetailsScreen.js.
HomeScreen.js
import React from 'react';
import { View, Text, Button } from 'react-native';
export default function HomeScreen({ navigation }) {
return (
<View>
<Text>Welcome to the Home Screen!</Text>
<Button title="Go to Details" onPress={() => navigation.navigate('Details')} />
</View>
);
}
DetailsScreen.js
import React from 'react';
import { View, Text } from 'react-native';
export default function DetailsScreen() {
return (
<View>
<Text>This is the Details Screen</Text>
</View>
);
}
4. Navigating with Parameters
You can pass parameters when navigating between screens. Modify the HomeScreen.js file:
<Button
title="Go to Details with Data"
onPress={() => navigation.navigate('Details', { message: 'Hello from Home!' })}
/>
Now, modify DetailsScreen.js to receive and display the parameter:
export default function DetailsScreen({ route }) {
return (
<View>
<Text>{route.params?.message}</Text>
</View>
);
}
5. Conclusion
With React Navigation, handling navigation in your React Native Expo app becomes simple and efficient. Whether you're building a small or large application, mastering navigation is essential. Try implementing different types of navigators like Tab Navigator and Drawer Navigator to enhance user experience! π

Comments
Post a Comment