Git Product home page Git Product logo

react-private-public-routes's Introduction

React-dom-router private & public routes with hooks.

React Router ships with a few hooks that let you access the state of the router and perform navigation from inside your components. I'm created a publicRoute & prvateRoute for user authentification, Private routes priotect with auth token PPublic routes are access without any authentication`.

Please note: You need to be using React >= 16.8 in order to use any of these hooks!

The main Route to navigate page.

import React, { useState, useMemo } from "react";
import { UserContext } from "./hooks/UserContext";
import { BrowserRouter, Switch } from 'react-router-dom';
import { Login, Home, PageOne, PageTwo, NoMatch } from './pages/'

import PublicRoute from './hooks/PublicRoute'
import PrivateRoute from './hooks/PrivateRoute'

function AppRouter() {
  const [user, setUser] = useState(null);

  const value = useMemo(() => ({ user, setUser }), [user, setUser]);

  return (

    <BrowserRouter>
      <UserContext.Provider value={value}>
        <Switch>
          <PublicRoute restricted={true} component={Login} path="/" exact />
          <PrivateRoute component={Home} path="/home" exact />
          <PrivateRoute component={PageOne} path="/page-1" exact />
          <PrivateRoute component={PageTwo} path="/page-2" exact />

          <PrivateRoute component={NoMatch} path="*" />
          <PublicRoute component={NoMatch} path="*" />

        </Switch>
      </UserContext.Provider>

    </BrowserRouter>
  );
}

export default AppRouter;

Private route allowes you only the page logged in.

import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import { isLogin } from '../middleware/auth';

const PrivateRoute = ({ component: Component, ...rest }) => (
    // Show the component only when the user is logged in
    // Otherwise, redirect the user to /signin page
    <Route {...rest} render={props => (isLogin() ? <Component {...props} /> : <Redirect to="/" />)} />
)

export default PrivateRoute;

Public route no need for the authentification it call access without login.

import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import { isLogin } from '../middleware/auth';

const PublicRoute = ({ component: Component, restricted, ...rest }) => (
    // restricted = false meaning public route
    // restricted = true meaning restricted route
    <Route {...rest} render={props => (isLogin() && restricted ? <Redirect to="/home" /> : <Component {...props} />)} />
)

export default PublicRoute;

Autthentication actions auth.js

// LOGIN
export const login = (props, d) => {
    if (d.username === 'user' && d.password === 'password') {
        localStorage.setItem('auth', d)
        props.history.push('/home');
    }
}

// LOGOUT
export const logout = () => localStorage.removeItem('auth')

// LOGIN STATUS
export const isLogin = () => {
    if (localStorage.getItem('auth')) return true;
    return false;
}

To install the project in your local device.

  • clone https://github.com/sreenathkspanikker/react-private-public-routes.git
  • npm install / yarn add
  • npm start / yarn start
  • username: user
  • password: password

react-private-public-routes's People

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.