React Navigation is a popular library for routing and navigation in Expo and React Native apps. It is simple to implement and allows for intricate customization to cater to varied navigation requirements.
The code snippet demonstrates the construction of screens using React Navigation:
import { NavigationContainer } from '@react-navigation/native'
import { createStackNavigator } from '@react-navigation/stack'
import SignupScreen from '../screens/SignupScreen'
const Stack = createStackNavigator();
export default function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Signup" component={SignupScreen} />
</Stack.Navigator>
</NavigationContainer>
)
}
createStackNavigator() function facilitates in creating an object containing 2 React components: Screen and Navigator.Navigator contains Screen elements as its children to define the configuration for routes. Each Screen is given a name to identify the screen and passed the actual React component; for example, SignupScreen that we built for this page.NavigationContainer is a component which manages our navigation tree and contains the navigation state used to store the navigation structure and history of the app, along with other useful functions that dispatch navigation actions.navigation PropEach screen component is provided with the navigation prop automatically. To navigate to a different screen, we can use the navigation.navigate() method like below:
export default function StartScreen({ navigation }) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Start Screen</Text>
<Button
title="Go to Signup"
onPress={() => navigation.navigate('Signup')}
/>
</View>
)
}