Created
October 6, 2017 07:52
-
-
Save dimapaloskin/8bc746f1526ffadb035d5ab64b80ad49 to your computer and use it in GitHub Desktop.
Mobx + react-router-dom 4 auth helper
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 React, { Component } from 'react' | |
import { | |
BrowserRouter as Router, | |
Route | |
} from 'react-router-dom' | |
import Auth from './Auth' | |
/* here mobx stuff */ | |
class App extends Component { | |
render () { | |
return ( | |
<Provider {...stores}> | |
<Router> | |
<div> | |
<Route exact path='/' component={Auth(AppRoute)} /> | |
<Route path='/login' component={Auth(LoginRoute)} /> | |
<Route path='/home' component={Auth(HomeRoute)} /> | |
</div> | |
</Router> | |
</Provider> | |
) | |
} | |
} | |
export default Root |
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 React from 'react' | |
import { Redirect } from 'react-router-dom' | |
import { inject, observer } from 'mobx-react' | |
import { PUBLIC_ROOT, PRIVATE_ROOT } from '../config' | |
const Resolver = (props) => { | |
const { isAuthenticated, component } = props | |
const { isPrivate } = component | |
let redirect | |
if (isAuthenticated && !isPrivate) { | |
redirect = PRIVATE_ROOT | |
} | |
if (!isAuthenticated && isPrivate) { | |
redirect = PUBLIC_ROOT | |
} | |
const Component = component | |
return redirect ? <Redirect to={redirect} /> : <Component {...props} /> | |
} | |
const Injected = inject(stores => ({ | |
isAuthenticated: stores.accountStore.isAuthenticated | |
}))(observer(Resolver)) | |
const Auth = (Comp) => props => { | |
return <Injected {...props} component={Comp} /> | |
} | |
export default Auth |
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 React, { Component } from 'react' | |
import { inject, observer } from 'mobx-react' | |
@inject(stores => ({ | |
username: stores.accountStore.account.username, | |
})) | |
@observer | |
class HomeRoute extends Component { | |
static isPrivate = true | |
render () { | |
const { username } = this.props | |
console.log(username) | |
return ( | |
<div>Hello {username}!</div> | |
) | |
} | |
} | |
export default HomeRoute |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment