So, I have an AdminScreen page where I have some headings and a ul and below that I want to define some links and when a user clicks on that link, I want to render some component (but I want the headings and ul of AdminScreen page to stay there).
In react router v5, I would just use switch and define my routes and it would work. But, I have no idea what to do with react router v6. I tried this:
<ul className="admin-functions">
<li>
<Link to="/admin/userslist"> Users List </Link>
</li>
<li>
<a href="/admin/pizzaslist"> Pizzas List </a>
</li>
<li>
<a href="/admin/addpizza"> Add New Pizza </a>
</li>
<li>
<a href="/admin/orderslist"> Orders List </a>
</li>
</ul>
<Routes>
<Route path="/admin/userslist" element={
<AdminRoute>
<UsersList />
</AdminRoute>
} />
<Route path="/admin/pizzaslist" element={
<AdminRoute>
<PizzasList />
</AdminRoute>
} />
</Routes>
But, it doesn't work.
Btw, AdminRoute is just the route for determining if the loggedIn user is admin. It's working fine on AdminScreen. Anyway, here's the code for it:
import { Navigate } from "react-router-dom";
import React from "react";
import { useSelector } from "react-redux";
const AdminRoute = ({ children }) => {
const loginUserReducer = useSelector((state) => state.loginUserReducer);
const { userInfo } = loginUserReducer;
const useAuth = () => {
const user =
localStorage.getItem("userInfo") && Object.entries(userInfo).length > 0;
if (user && userInfo.isAdmin) {
return true;
} else {
return false;
}
};
const auth = useAuth();
return auth?children: <Navigate to="/login"/>
};
export default AdminRoute;
P.S: How do I use react router v6 to switch between components on one parent component doesn't answer my question
So, I figured it out:
In my App.js, add a wildcard to the link of admin screen component:
<Route path="/admin/*" element={
<AdminRoute>
<AdminScreen />
</AdminRoute>
} />
In AdminScreen component, change route paths to:
<Route path="userslist" element={
<AdminRoute>
<UsersList />
</AdminRoute>
} />