-
-
Save soundyogi/f0a5309cc98062638e750049ffe1b93e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { matchPath } from 'react-router'; | |
| class MainRouter extends Component { | |
| static displayName = 'MainRouter'; | |
| static propTypes = { | |
| store: React.PropTypes.object, | |
| component: React.PropTypes.oneOfType([ | |
| React.PropTypes.element, | |
| React.PropTypes.func, | |
| ]) | |
| }; | |
| render() { | |
| const { component, store } = this.props; | |
| const requireAuth = (state) => !isSignedIn(state) ? '/login': null; | |
| const requireNotAuth = (state) => isSignedIn(state) ? '/' : null; | |
| const createSelectLocationState = () => { | |
| let prevRoutingState, prevRoutingStateJS; | |
| return (state) => { | |
| const routingState = state.get('routing'); | |
| if (typeof prevRoutingState === 'undefined' || !prevRoutingState.equals(routingState)) { | |
| prevRoutingState = routingState; | |
| prevRoutingStateJS = routingState.toJS(); | |
| } | |
| return prevRoutingStateJS; | |
| }; | |
| }; | |
| return ( | |
| <Router history={history}> | |
| <App> | |
| <CustomSwitch store={store}> | |
| <Route path="/" exact={true} component={Index} /> | |
| <Route path="/login" component={Login} onEnter={requireNotAuth} /> | |
| <Route path="/register" component={Register} onEnter={requireNotAuth} /> | |
| <Route component={ErrorNotFound} /> | |
| </CustomSwitch> | |
| </App> | |
| </Router> | |
| ); | |
| } | |
| } | |
| class CustomSwitch extends Switch { | |
| render() { | |
| const { route } = this.context.router; | |
| const { children, store } = this.props; | |
| const location = this.props.location || route.location; | |
| let match, child; | |
| let foundRedirect = false; | |
| React.Children.forEach(children, element => { | |
| if (!React.isValidElement(element)) return; | |
| if (foundRedirect) return; | |
| const { path: pathProp, exact, strict, from, onEnter } = element.props; | |
| const path = pathProp || from; | |
| if (match == null) { | |
| child = element; | |
| match = path ? matchPath(location.pathname, { path, exact, strict }) : route.match; | |
| if (match && onEnter) { | |
| const returnedValue = onEnter(store.getState()); | |
| if (returnedValue) { | |
| browserHistory.push(returnedValue); | |
| foundRedirect = true; | |
| } | |
| } | |
| } | |
| }); | |
| return match ? React.cloneElement(child, { location, computedMatch: match }) : null; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment