Using React Router Dom I have run into a problem.
Suppose I want to enter a profile page, but the user must be logged in before entering. So, in this case I’m using Navigate to redirect the user to Home, in case they’re not logged in. But my problem is that I want to show an alert to the user specifying that he must log in first before entering the profile page.
import React from "react";
import {
BrowserRouter as Router,
Link,
Route,
Routes,
Navigate,
} from "react-router-dom";
import NotFoundPage from "./pages/404/NotFoundPage";
import AboutPage from "./pages/about-faqs/AboutPage";
import HomePage from "./pages/home/HomePage";
import ProfilePage from "./pages/profile/ProfilePage";
import ProtectedRoute from "./pages/Protected-Routes/protectedRoute";
import TaskDetailPage from "./pages/tasks/TaskDetailPage";
import TasksPage from "./pages/tasks/TasksPage";
function AppRoutingOne() {
const logged = false;
return (
<Router>
<div>
<ul style={{ display: "flex", justifyContent: "space-between" }}>
<li>
<Link to="/"> Home </Link>
</li>
<li>
<Link to="/about"> About </Link>
</li>
<li>
<Link to="/faqs"> FAQs </Link>
</li>
</ul>
</div>
<main>
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/about" element={<AboutPage />} />
<Route path="/faqs" element={<AboutPage />} />
//This is the part of my problem, in this case. How do I display an "alert()" inside the ternary operator?
<Route
path="/profile"
element={logged ? <ProfilePage /> : <Navigate to="/" replace /> }
/>
<Route path="/task" element={<TasksPage />} />
<Route path="/task/:id" element={<TaskDetailPage />} />
{/* 404 - Page Not Found */}
<Route path="*" element={<NotFoundPage />} />
</Routes>
</main>
</Router>
);
}
export default AppRoutingOne;
2
Answers
I edit add to your code , and add new Component :
in this component you check logged props. if logged is false you can show alert to user :
App.js
Outlet will be the component that have been in the children route !