codica2 / react-authorized-routes-sample

⚛️ React authorized routes with HOC sample

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

React authorized routes with HOC sample

Description

This is an example of the HOC for managing autorized, unauthorized, common etc. routes in you react application.

Firstly, we create and export a few constants, we are going to use them to define the type of a route.

export const SHARED = "SHARED";
export const LOGGED = "LOGGED";
export const UNLOGGED = "UNLOGGED";

SHARED - means that both autorized and unauthorized users can get access to the current route
LOGGED - only autorized users
UNLOGGED - only unauthorized users

Also we should define a current user state, in our example has been used React Context API, particularly useContext hook but of course, you may use anything you want instead (Redux, MobX, etc.).

const { user } = useContext(AuthContext);

const logged = user ? LOGGED : UNLOGGED;

Then we set a case when a user must be redirected to the login page otherwise we just do nothing and return the actual component that has been passed as an argument.

if (auth !== SHARED && auth !== logged) {
  return <Redirect to="/login" />;
}

return <Component {...rest} />;

Here is a full example:

export const SHARED = 'SHARED';
export const LOGGED = 'LOGGED';
export const UNLOGGED = 'UNLOGGED';

export default auth => Component => props => {
  const { user } = useContext(AuthContext);

  const logged = user ? LOGGED : UNLOGGED;

  if (auth !== SHARED && auth !== logged) {
    return <Redirect to="/login" />
  }

  return <Component {...rest} />

Usage

In order to use it at first invocation, we pass the auth constant and then we must pass the actual component.

import Homepage from '../pages/home';
import Login from '../pages/login';
import Register from '../pages/register';
import Profile from '../pages/profile';

const shared = auth(SHARED);
const logged = auth(LOGGED);
const unlogged = auth(UNLOGGED);

const Auth = {
  Homepage: shared(Homepage),
  Login: unlogged(Login),
  Register: unlogged(Register),
  Profile: logged(Profile),
};

const App = () => (
  <Switch>
    <Route exact path="/" component={Auth.Homepage} />
    <Route exact path="/login" component={Auth.Login} />
    <Route exact path="/register" component={Auth.Register} />
    <Route exact path="/profile" component={Auth.Profile} />
  </Switch>
);

Or if you prefer declatative object-based approach with react-router:

// ...

const routes = [
  {
    path: '/homepage',
    auth: shared,
    component: Homepage,
  },
  {
    path: '/login',
    auth: unlogged,
    component: Login,
  },

  // ...
];

About Codica

Codica logo

We love open source software! See our other projects or hire us to design, develop, and grow your product.

About

⚛️ React authorized routes with HOC sample