usman9023's avatar

Authentication In React Js

im trying to implement unauthenticated user to access the /login route and prevent an authenticated user from accessing it, and allow an authenticated user to access the /dashboard route and prevent an unauthenticated user from accessing it. here is my UserAuth component code

import React, { Component } from 'react';
import { Redirect } from 'react-router-dom';

const UserAuth = (WrappedComponent) => {
  return class extends Component {
    render() {
      const accessToken = localStorage.getItem('access_token');
      if (!accessToken || accessToken.length === 0){
        
        return <Redirect to="/login" />;

      }
      if (accessToken && accessToken.length > 0) {
       
        return <Redirect to="/dashboard" />;
      }
      return <WrappedComponent {...this.props} />;
    }
  }
}

export default UserAuth;

and here is my APP.js code

import Login from "./components/Login";
import { Route } from "react-router-dom";
import Dashboard from "./components/Dashboard";
import UserAuth from "./components/UserAuth";
import { BrowserRouter } from "react-router-dom";
import { Switch } from "react-router-dom";
function App() {
  const LoginWithAuth = UserAuth(Login);
  const DashboardWithAuth = UserAuth(Dashboard);
  return (
    <BrowserRouter>
      <Switch>
        <Route exact path="/" component={LoginWithAuth} />
        <Route  path="/login" component={LoginWithAuth} />
        <Route  path="/dashboard" component={DashboardWithAuth} />
      </Switch>
    </BrowserRouter>
  );
}

export default App;

The logic is fine but none of my component is rendering only white blank page is rendering and none of the error occurs in console. Any idea what am i doing wrong thanks

0 likes
1 reply
Randy_Johnson's avatar

You could also just use Laravel Breeze which will set all this up for you.

Please or to participate in this conversation.