Skip to content

Instantly share code, notes, and snippets.

@harish2704
Created May 22, 2016 15:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harish2704/082d153ec3847bf4aa5ee847a3c33661 to your computer and use it in GitHub Desktop.
Save harish2704/082d153ec3847bf4aa5ee847a3c33661 to your computer and use it in GitHub Desktop.
Simple react-native-redux-router
import React, { Component } from 'react';
import {
Text,
View,
LayoutAnimation,
UIManager
} from 'react-native';
UIManager.setLayoutAnimationEnabledExperimental && UIManager.setLayoutAnimationEnabledExperimental(true);
export function Route( ){ return <Text>This is Route</Text>; }
export class Router extends Component{
constructor( props ){
super();
let routeData = {};
React.Children.forEach( props.children, ( child, index ) =>{
let { name, component } = child.props;
let route = {
component: component,
name: name,
};
routeData[name] = route;
});
this.routeData = routeData;
this.initial = routeData[ props.initial ];
}
componentWillUpdate() {
LayoutAnimation.configureNext( LayoutAnimation.Presets.spring );
}
componentDidMount(){
this.context.store.dispatch({
type: 'ROUTER_PUSH',
payload: {
name: this.initial.name
}
});
}
render(){
var store = this.context.store.getState();
let routes = store.router.routes;
LayoutAnimation.configureNext(LayoutAnimation.Presets.spring);
if( !routes.length ){
return <Text>Loading..</Text>;
}
let routeName = routes[ routes.length -1 ];
let route = this.routeData[ routeName ];
return <route.component />;
}
}
Router.contextTypes = {
store: React.PropTypes.object.isRequired
};
const initialRouteState = {
routes: [],
}
export function reducer( state = initialRouteState, action ){
let stack = state.routes.slice();
switch( action.type ){
case 'ROUTER_PUSH':
stack.push( action.payload.name );
break;
case 'ROUTER_POP':
stack.pop();
break;
}
return {
...state,
routes: stack,
};
}
/* Dummy Fn */
export function Schema(){ return <View></View>; }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment