Push Navigation
Defining States
After following the Setup instructions, you end up with an empty StateNavigator
in App.js
. The StateNavigator
accepts an array of States that represent the scenes in your application. In an email application, for example, we might have States
representing the inbox scene and the scenes for reading and writing a mail.
Both Android and iOS allow a user to navigate back through their stack of visited scenes. The Navigation router manages this stack by dropping a breadcrumb at each visited scene, like the fairy-tale characters Hansel and Gretel. You enable the breadcrumb trail by setting trackCrumbTrail
to true against each State
. In an email application, we set trackCrumbTrail
to true on the 'mail' State
so that the user can return to the 'inbox' scene after opening an email.
const stateNavigator = new StateNavigator([
{key: 'inbox'},
{key: 'mail', trackCrumbTrail: true},
{key: 'compose', trackCrumbTrail: true}
]);
Creating Scenes
Each State
needs a matching scene which the NavigationStack
displays when that State
is active. You wrap each one in a Scene
component and pass the key of the State
to the stateKey prop
. We can create the scenes in our email application using Inbox
, Mail
and Compose
components.
import {Scene} from 'navigation-react-native';
<NavigationStack>
<Scene stateKey="inbox"><Inbox /></Scene>
<Scene stateKey="mail"><Mail /></Scene>
<Scene stateKey="compose"><Compose /></Scene>
</NavigationStack>
Pushing
States
become active by navigating to them. You navigate to a State
by passing the State key
to the navigate
function of the StateNavigator
. You can access the StateNavigator
inside any component using the React Context API. In our email example, we can add a button to the 'inbox' scene that navigates to the 'compose' State
. Pressing the button pushes the 'compose' scene onto the stack. The user can return to their inbox using the Android back button or by pressing/swiping back on iOS.
import {NavigationContext} from 'navigation-react';
const Inbox = () => {
const {stateNavigator} = useContext(NavigationContext);
return (
<Button
title="Compose Mail"
onPress={() => {
stateNavigator.navigate('compose');
}} />
);
};
Passing Data
You pass data between scenes via the second parameter of the navigate
function. You can pass any data of type string, number, boolean and date; or any array of these types. When a user opens an email in our example app, we pass along the selected id to the 'mail' scene.
<Button
title="Open Mail"
onPress={() => {
stateNavigator.navigate('mail', {id: 12});
}} />
In the 'mail' scene we get the selected id from the NavigationContext
.
import {NavigationContext} from 'navigation-react';
const Mail = () => {
const {data} = useContext(NavigationContext);
const {id} = data;
}
Note
Wrap each scene in aSafeAreaView
component or a ScrollView
component with contentInsetAdjustmentBehavior
set to 'automatic' to prevent the iOS navigation bar overlapping the content