Skip to content

Instantly share code, notes, and snippets.

@nijjwal
Created October 10, 2022 09:04
Show Gist options
  • Save nijjwal/397ddbab96d353f9febe21b272352a4f to your computer and use it in GitHub Desktop.
Save nijjwal/397ddbab96d353f9febe21b272352a4f to your computer and use it in GitHub Desktop.
React - Private Route - Protecting Dashboard with a Wrapper Class
//Code for PrivateRoute.js
import React from "react";
import { Navigate } from "react-router-dom";
import { useAuth } from "../contexts/AuthContext";
export default function PrivateRoute({ children }) {
const { currentUser } = useAuth();
return currentUser ? children : <Navigate to="/login" />;
}
//Code for Dashboard element in your app.js
{/* Wrap the Component that needs authentication with PrivateRoute*/}
<Route path="/" element={<PrivateRoute> <Dashboard /></PrivateRoute>}></Route>
<Route path="/dashboard" element={<PrivateRoute> <Dashboard /></PrivateRoute>}></Route>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment