Hello React Navigation
In a web browser, you can link to different pages using an anchor (<a>) tag. When the user clicks on a link, the URL is pushed to the browser history stack. When the user presses the back button, the browser pops the item from the top of the history stack, so the active page is now the previously visited page. React Native doesn't have a built-in idea of a global history stack like a web browser does -- this is where React Navigation enters the story.
React Navigation's stack navigator provides a way for your app to transition between screens and manage navigation history. If your app uses only one stack navigator then it is conceptually similar to how a web browser handles navigation state - your app pushes and pops items from the navigation stack as users interact with it, and this results in the user seeing different screens. A key difference between how this works in a web browser and in React Navigation is that React Navigation's stack navigator provides the gestures and animations that you would expect on Android and iOS when navigating between routes in the stack.
Lets start by demonstrating the most common navigator, createStackNavigator.
Creating a stack navigator
createStackNavigator is a function that returns a React component. It takes a route configuration object and, optionally, an options object (we omit this below, for now). Because the createStackNavigator function returns a React component, we can export it directly from App.js to be used as our App's root component.
// In App.js in a new project
import React from 'react';
import { View, Text } from 'react-native';
import { createStackNavigator, createAppContainer } from 'react-navigation';
class HomeScreen extends React.Component {
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
</View>
);
}
}
const AppNavigator = createStackNavigator({
Home: {
screen: HomeScreen,
},
});
export default createAppContainer(AppNavigator);
→ Run this code
If you run this code, you will see a screen with an empty navigation bar and a white content area containing your HomeScreen component. The styles you see for the navigation bar and the content area are the default configuration for a stack navigator, we'll learn how to configure those later.
The casing of the route name doesn't matter -- you can use lowercase
homeor capitalizedHome, it's up to you. We prefer capitalizing our route names.