State Navigation

Defining States

The Navigation router helps you navigate between views in your application. To get started, create a new StateNavigator passing in an array of States that represent the views in your application. Assign the empty route to the State you want to show when the application first loads. You can put off assigning the other routes until your application is up and running. In an email application we might have States representing the inbox and the views for reading and writing an email.

var stateNavigator = new Navigation.StateNavigator([
  {key: 'inbox', route: ''},
  {key: 'mail'},
  {key: 'compose'}
]);

Defining Views

Each State needs a matching view which you’ll display when that State is active. You define the view in a function attached to the renderView property of the State. We can define two of the views in the email example using Inbox and Compose components.

stateNavigator.states.inbox.renderView = function() {
  return <Inbox />;
};

stateNavigator.states.compose.renderView = function() {
  return <Compose />;
};

Calling start on the stateNavigator activates the State whose route matches with the browser Url. In our example, the 'inbox' State will be active on first load.

stateNavigator.start();

Rendering

It's your job to keep the UI up to date by calling the renderView function on the active State. You render a NavigationContext Consumer with a child prop that returns the view of the passed in State. Wrapping the Consumer inside a NavigationHandler ensures that every time the State changes your child render prop is called with the new State. Make sure you pass data into the renderView function otherwise this rendering code will break when it comes to passing navigation data between States.

ReactDOM.render(
  <NavigationReact.NavigationHandler stateNavigator={stateNavigator}>
    <NavigationReact.NavigationContext.Consumer>
      {({ state, data }) => state.renderView(data)}
    </NavigationReact.NavigationContext.Consumer>
  </NavigationReact.NavigationHandler>,
  document.getElementById('app')
);

Navigating

States become active when you navigate to them. One way to navigate to a State is with a Hyperlink. The Navigation router encourages you to think about States rather than Urls. You can build Hyperlinks using the NavigationLink component, passing in the destination State via the stateKey prop.

<NavigationReact.NavigationLink stateKey="compose">
  Compose Mail
</NavigationReact.NavigationLink>

When Hyperlinks aren't appropriate, you can navigate programmatically by passing the State key into the navigate function on the stateNavigator. You can access the stateNavigator inside the child render prop of a NavigationContext Consumer.

<NavigationReact.NavigationContext.Consumer>
  {({ stateNavigator }) => (
    <div onClick={() => stateNavigator.navigate('compose')}>Compose Mail</div>
  )}
</NavigationReact.NavigationContext.Consumer>