Skip to content

Instantly share code, notes, and snippets.

@EmperorEarth
Last active February 1, 2016 17:05
Show Gist options
  • Save EmperorEarth/474373cb16b006fc8fbc to your computer and use it in GitHub Desktop.
Save EmperorEarth/474373cb16b006fc8fbc to your computer and use it in GitHub Desktop.
React-Router's onEnter <> requireAuth read from Redux store
// Comment: http://stackoverflow.com/questions/33643290/how-do-i-get-a-hold-of-the-store-dispatch-in-react-router-onenter/34278483#34278483
// User: http://stackoverflow.com/users/184532/kjs3
// because versions matter
babel-polyfill (^6.3.14)
presets: es2015, react, stage-2
react (^0.14.7), react-dom (^0.14.7),
redux (^3.1.2), react-redux (^4.1.1),
react-router (^2.0.0-rc5), react-router-redux (^2.1.0)
import React, { Component } from 'react'
import { Provider } from 'react-redux'
import { Router, browserHistory } from 'react-router'
import routes from './routes'
import DevTools from './parts/DevTools'
import configureStore from './store/configureStore'
const store = configureStore()
export default class Root extends Component {
render() {
return (
<Provider store={store}>
<div>
<Router history={browserHistory}>
{routes(store)}
</Router>
<DevTools />
</div>
</Provider>
)
}
}
import React from 'react'
import { Route } from 'react-router'
import App from './App'
import Private from './parts/Private'
import Public from './parts/Public'
import LoginWidgetContainer from './parts/session/login/Container'
import RegisterWidgetContainer from './parts/session/register/Container'
export default (store) => {
const reqAuth = (nextState, replace) => {
const { isAuth } = store.getState().session
if (!isAuth) {
replace({
pathname: '/login',
state: {
nextPathname: nextState.location.pathname,
},
})
}
}
return (
<Route path="/" component={App}>
<Route path="/login" component={LoginWidgetContainer} />
<Route path="/register" component={RegisterWidgetContainer} />
<Route path="/public" component={Public} />
<Route onEnter={reqAuth}>
<Route path="/private" component={Private} />
</Route>
</Route>
);
}
@EmperorEarth
Copy link
Author

I'll edit this later to have transition/redirect backs
Another plan I had was to optionally raise a login modal too.

When I grok all this better, I'll post a boilerplate, with a client-only branch and a universal branch

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment