Skip to content

Instantly share code, notes, and snippets.

@jbpin
Last active August 13, 2016 15:00
Show Gist options
  • Save jbpin/a8f804c51968da8d2b40663933931b42 to your computer and use it in GitHub Desktop.
Save jbpin/a8f804c51968da8d2b40663933931b42 to your computer and use it in GitHub Desktop.
import React, { Component, Children } from 'react';
import { NavigationExperimental } from 'react-native';
import navigationStore from '../navigationStore';
const {
CardStack: NavigationCardStack,
} = NavigationExperimental;
export default class NavigationRoot extends Component {
constructor(props) {
super(props);
this.scenes = {};
}
componentWillMount() {
this.initNavigation(this.props);
navigationStore.changed.add(this.onNavigationUpdated.bind(this));
}
componentWillReceiveProps(nextProps) {
if (nextProps.children !== this.props.children) {
this.initNavigation(nextProps);
}
}
onNavigationUpdated() {
this.setState({ ...this.state, ...navigationStore.getState() });
}
initNavigation(props) {
Children.map(props.children, (element) => {
if (element.props.routeKey) {
this.scenes[element.props.routeKey] = element;
}
});
let initial = null;
if (!this.state || (!this.state.routes && !this.state.routes.length)) {
navigationStore.push({ key: props.initialRoute });
initial = { routes: [{ key: props.initialRoute }] };
}
this.setState({ ...navigationStore.getState(), ...initial });
}
renderScene(props) {
const element = this.scenes[props.scene.route.key];
if (!element) {
throw new Error(`element for key ${props.scene.route.key} not found`, props);
}
element.props = { ...props, ...element.props };
return element;
}
render() {
return (
<NavigationCardStack {...this.props}
renderScene={(props) => this.renderScene(props)}
navigationState={this.state}
/>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment