Created
October 10, 2022 09:04
-
-
Save nijjwal/397ddbab96d353f9febe21b272352a4f to your computer and use it in GitHub Desktop.
React - Private Route - Protecting Dashboard with a Wrapper Class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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