Skip to content

Instantly share code, notes, and snippets.

@lucnat
Last active August 21, 2019 00:42
Show Gist options
  • Save lucnat/643988451c783a8428a2811dbea3d168 to your computer and use it in GitHub Desktop.
Save lucnat/643988451c783a8428a2811dbea3d168 to your computer and use it in GitHub Desktop.
Meteor React-Router Accounts
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);
@lucnat
Copy link
Author

lucnat commented Jan 11, 2019

Explanation:

  • public components are visible by everyone, they use the PublicLayout
  • authenticated components are visible by authenticated users only - they use the AuthenticatedLayout

We could have an arbitrary number of layouts. In the example above, there are two layouts - each with it's own navbar.

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