Last active
August 21, 2019 00:42
-
-
Save lucnat/643988451c783a8428a2811dbea3d168 to your computer and use it in GitHub Desktop.
Meteor React-Router Accounts
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 { Meteor } from 'meteor/meteor'; | |
import React from 'react'; | |
import { withTracker } from 'meteor/react-meteor-data'; | |
import { BrowserRouter, Route, Link, Redirect, withRouter, Switch} from "react-router-dom"; | |
// pages accessible to all users | |
import Home from './Home'; | |
import Login from './Login'; | |
// pages accessible to authenticated users only | |
import Profile from './Profile'; | |
export let AppRoute = ({ component: Component, layout: Layout, ...rest }) => ( | |
<Route {...rest} render={props => ( | |
<Layout> | |
<Component {...props} /> | |
</Layout> | |
)} /> | |
); | |
const PublicNavbar = () => (<div style={{height: 50, borderBottom: '1px solid black'}}> Navbar </div>); | |
const AuthenticatedNavbar = () => (<div style={{height: 50, borderBottom: '1px solid black'}}> Authenticated Nav </div>); | |
class PublicLayout extends React.Component { | |
render() { | |
return ( | |
<div> | |
<PublicNavbar /> | |
{this.props.children} | |
</div> | |
); | |
} | |
} | |
class AuthenticatedLayout extends React.Component { | |
render() { | |
if(Meteor.user()) return ( | |
<div> | |
<AuthenticatedNavbar /> | |
{this.props.children} | |
</div> | |
); | |
return ( | |
<div> | |
<Login /> | |
</div> | |
); | |
} | |
} | |
class Router extends React.Component { | |
render() { | |
return ( | |
<BrowserRouter> | |
<Switch> | |
// public routes | |
<AppRoute exact path="/" layout={PublicLayout} component={Home} /> | |
<AppRoute exact path="/login" layout={PublicLayout} component={Login} /> | |
// logged in routes | |
<AppRoute exact path="/profile" layout={AuthenticatedLayout} component={Profile} /> | |
</Switch> | |
</BrowserRouter> | |
); | |
} | |
} | |
export default withTracker(props => { | |
return { | |
user: Meteor.user() | |
} | |
})(Router); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Explanation:
PublicLayout
AuthenticatedLayout
We could have an arbitrary number of layouts. In the example above, there are two layouts - each with it's own navbar.