Skip to content

Instantly share code, notes, and snippets.

@thulioph
Last active March 13, 2019 23:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thulioph/1088965694a407107346ff6e77bed80a to your computer and use it in GitHub Desktop.
Save thulioph/1088965694a407107346ff6e77bed80a to your computer and use it in GitHub Desktop.
Example of a HOC to manage route permissions in React.
import React from 'react';
import ReactDOM from 'react-dom';
import Routes from './routes';
ReactDOM.render(
<React.Fragment>
<Routes />
</React.Fragment>
, document.getElementById('root')
);
import React from 'react';
import { withRouter, Redirect } from 'react-router-dom';
const PrivateRoute = (WrappedComponent) => {
class PrivateRoute extends React.Component {
state = {
isLogged: false,
}
_checkAuthentication() {
const logged = null;
if (logged) {
this.setState({ isLogged: true }, () => {
console.warn('user is logged!');
});
}
}
componentWillMount() {
this._checkAuthentication();
}
componentWillReceiveProps(nextProps) {
if (nextProps.location !== this.props.location) {
this._checkAuthentication();
}
}
render() {
const { isLogged } = this.state;
if (!isLogged) {
return (
<Redirect
to={{
pathname: '/login',
state: { from: this.props.location }
}}
/>
);
}
return (
<WrappedComponent {...this.props} />
);
}
}
return withRouter(PrivateRoute);
}
export default PrivateRoute;
import React from 'react';
import { Router, Switch, Route } from 'react-router-dom';
import createBrowserHistory from 'history/createBrowserHistory';
import PrivateRoute from './private';
import Base from './containers/base';
import Login from './containers/login';
import App from './containers/app';
import NotFound from './containers/notfound';
const Routes = () => (
<Router history={createBrowserHistory()}>
<Switch>
<Route exact path="/" component={Base} />
<Route path="/login" component={Login} />
<Route path="/app" component={PrivateRoute(App)} />
<Route component={NotFound} />
</Switch>
</Router>
);
export default Routes;