Hello World

The Navigation router uses the underlying native APIs to provide faithful navigation on Android and iOS. It's the only React Native router that offers native navigation where the stack can be interrogated in JavaScript. The best of both worlds. We're going to build an example with two scenes. The first scene will show a button that says 'Hello'. Pressing the button will push a second scene onto the stack. This scene will display a button that says 'World'. Pressing it will pop the second scene off the stack and return you to the first.

After following the Setup instructions, we'll add two States to the StateNavigator array in App.js . There's one State for the 'hello' scene and another for the 'world' scene. The Navigation router manages the stack as a 'breadcrumb trail'. Named after the trail of breadcrumbs Hansel and Gretel dropped to remember their journey back, each breadcrumb in the trail represents a scene in the stack. We'll enable the breadcrumb trail by setting trackCrumbTrail to true on the 'world' State.

var stateNavigator = new StateNavigator([ {key: 'hello'}, {key: 'world', trackCrumbTrail: true} ]);

Push

We push scenes onto the stack by navigating to States . We want to display the 'hello' scene first so we'll start by navigating to the 'hello' State .

stateNavigator.navigate('hello');

The Navigation router displays the scene we return from the renderScene function of the 'hello' State . The scene consists of a button that says 'Hello'. When pressed, we want to push the 'world' scene onto the stack. We'll access the stateNavigator using the React Context API and navigate to the 'world' State inside the onPress handler. The navigate function accepts navigation data as the second parameter. We’ll use it to pass across a size of 20 to the 'world' scene.

import {NavigationContext} from 'navigation-react'; var {hello} = stateNavigator.states; hello.renderScene = () => { var {stateNavigator} = useContext(NavigationContext); return ( <TouchableHighlight onPress={() => { stateNavigator.navigate('world', {size: 20}); }}> <Text>Hello</Text> </TouchableHighlight> ); };

We build the 'world' scene inside the renderScene function of the 'world' State . We'll destructure the size from the incoming navigation data and assign it to Text component’s font size.

var {world} = stateNavigator.states; world.renderScene = ({size}) => ( <Text style={{fontSize: data.size}}>World</Text> );

Pop

We pop scenes off the stack by navigating backwards. How far we navigate back determines the number of scenes popped. We'll change the 'world' scene so that it renders a button instead of plain text. Inside the onPress handler, we'll call the navigateBack function passing in a distance of 1. Because the Navigation router uses the underlying native APIs, you can also return to the 'hello' scene using the back button on Android or by swiping/pressing back on iOS.